Asked  7 Months ago    Answers:  5   Viewed   35 times

I have database consists of countries and cities.

First Case - Successfully done:

  1. Country list gets populated in drop box on page load
  2. City list gets populated in drop box on page load - populated city list is based on the default country.

Second Case - Couldn't make it:

  1. User changes country
  2. City list will be changed according to selected country

I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.

I'm using regular PHP coding style, not Object-Oriented.

How can i do it? Any related resources will be appreciated.

 Answers

86
$("#country").change(function(){
    $('#city').find('option').remove().end(); //clear the city ddl
    var country = $(this).find("option:selected").text();
    alert(country);
    //do the ajax call
    $.ajax({
        url:'getCity.php'
        type:'GET',
        data:{city:country},
        dataType:'json',
        cache:false,
        success:function(data){

        data=JSON.parse(data); //no need if dataType is set to json
         var ddl = document.getElementById('city');                      

         for(var c=0;c<obj.length;c++)
              {              
               var option = document.createElement('option');
               option.value = obj[c];
               option.text  = obj[c];                           
               ddl.appendChild(option);
              }


    },
        error:function(jxhr){
        alert(jxhr.responseText);

    }
    }); 

});

in your getCity.php

$country = $_GET['city'];

//do the db query here

$query  = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {

 if(empty($temp))
 {
   $temp=array($row['city']);
 }
 else
 {  
   array_push($temp,$row['city']);
 }

}
echo (json_encode($temp));
Wednesday, March 31, 2021
 
keisar
answered 7 Months ago
36

base64 encode the image and return that, then you can do an <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA......." />

On the PHP side

$image = base64_encode($imageGDRender);
echo json_encode(array('image'=>$image));

That will return your json back to your jquery

then on the ajax side

$.ajax({
    ...
    success: function(data) {
        var base64Image = data.image;
        ...now put it in your image
        $('#image').attr('src','data:image...'+base64Image);
    })....
Friday, May 28, 2021
 
scessor
answered 5 Months ago
74

The easiest way would to use the Phery library http://phery-php-ajax.net/ the key here is the data-phery-remote="toggle" that will call the PHP function automatically on click, and can be reused everywhere

<span class="searchitem">
  // some visible content here 
  <span value="item name" data-phery-remote="toggle" class="btn">button</span>
  <span class="slide_area">
  // hidden slide content ajax needs to populate with php result
  </span>
</span>

The logic is reversed, the load will happen with only one AJAX call, instead of two.

Phery::instance()->set(array(
  'toggle' => function($data){
    $r = new PheryResponse;
    /* do your code, fill $html_content */
    $r->this()->siblings('.slide_area')->html($html_content)->toggle();
    return $r;
  }
))->process();
Saturday, May 29, 2021
 
ammezie
answered 5 Months ago
100

Consider following the steps & lines of code to open the url & click on a menu:

  • Install current version of selenium through pip
  • Download the latest chromedriver.exe and provide the absolute path in your script
  • Code Block:

    from selenium import webdriver
    driver=webdriver.Chrome("C:\Utility\your_directory\chromedriver.exe")
    #maximize the browser window
    driver.maximize_window()
    #open the url in the browser
    driver.get("https://www.mirrorfiction.com/zh-Hant/book/406")
    #click on the first menu item ??
    driver.find_element_by_xpath("//nav[@id='nav']/div/ul/li/a/span[@class='text novel']").click()
    
Sunday, June 20, 2021
 
Blur
answered 4 Months ago
43

You can use the built-in MVC validation scripts along with the data annotaions on your model

public class AccountProfileEditViewModel
{
    [Display(Name = "Address")]
    [Required()]
    [StringLength(200)]
    public string Address { get; set; }
}

Make a partial view to hold your modal form.

_AccountProfileEdit.cshtml

@model AccountProfileEditViewModel

@using(Html.BeginForm("AccountProfileEdit", "Account",
           FormMethod.Post, new { id = "form-accountedit-appt" }) {
    @Html.ValidationSummary(true)

    @Html.LabelFor(m => m.Address)
    @Html.TextBoxFor(m => m.Address)
    @Html.ValidationMessageFor(m => m.Address)
    <button type="submit">Edit</button>
}

Then reference this in your modal box. If you want pre-populated model you'll need to render an action:

<div class="modal-body" id="form-container">
    @Html.Action("AccountProfileEdit", "Account", new { id=account.Id })
</div>

If you just want a blank form then you can just use:

<div class="modal-body" id="form-container">
    @Html.Partial("_AccountProfileEdit")
</div>

The action uses the id parameter to fetch and populate the model

[HttpGet]
public ActionResult AccountProfileEdit(int id)
{
    AccountProfileEditViewModel model = db.GetAccount(id);  // however you do this in your app

    return PartialView("_AccountProfileEdit", model);
}

AJAX POST

Now you'll need AJAX to submit this form. If you rely on a standard form submission the browser will navigate away from your page (and close your modal).

$("#myModal").on("submit", "#form-accountedit", function(e) {
    e.preventDefault();  // prevent standard form submission

    var form = $(this);
    $.ajax({
        url: form.attr("action"),
        method: form.attr("method"),  // post
        data: form.serialize(),
        success: function(partialResult) {
            $("#form-container").html(partialResult);
        }
    });
});

You need to use the event delegate $(staticParent).on(event, target, handler) for the submit event because the form content may be replaced later.

Post Action

[HttpPost]
public ActionResult AccountProfileEdit(AccountProfileEditViewModel model)
{
    // Request.Form is model

    if (ModelState.IsValid)
    {
        // do work
        return PartialView("_AccountEditSuccess");
    }

    return PartialView("_AccountProfileEdit", model);
}

Client-side validation scripts should prevent them from ever submitting. But if that somehow failed or if you can't validate something on the client then you have ModelState.IsValid. You might also invalidate something server-side manually.

_AccountEditSuccess.cshtml

And the "success" partial view.

<div>Success! <button>Click to close</button></div>

Not Valid is a Fail, Right?

From your AJAX success handler you have

success: function(partialResult) {
    $("#form-container").html(partialResult);
}

But the problem here is we don't know if you are getting a "success" or "validation failure". Adding an error: function(err){ } handler won't help because the validation failure is considered a HTTP 200 response. In both cases the div content is replaced the user will need to manually close the modal. There are ways to pass additional data to distinguish both conditions but that's another long answer post.

Tuesday, July 27, 2021
 
ALH
answered 3 Months ago
ALH
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :