Skip to content Skip to sidebar Skip to footer

Some Ajax Help?

I have a php script that takes some user form input and packs some files into a zip based on that input. The problem is that sometimes the server errors, so all the form data is lo

Solution 1:

How do you set up returns in the PHP file

just echo it in ajax page that will return as response

Simple Tutorial

client.php

$.post('server.php',({parm:"1"}) function(data) {
  $('.result').html(data);
});

server.php

<?php

echo $_POST['parm'];

?>

result will be 1

edit on OP comments Is there a way to use ajax as if you were submitting a form

Yes, there is

using sumit

$('#form').submit(function() {
 //your ajax call
  return false;
});

Solution 2:

every ajax function has a function param to deal with server returns.and most of them has the param msg,that is the message from server. server pages for example php pages you can just use echo something to return the infomation to the ajax funciton . below is an example

$.ajax({
  url:yoururl,
  type:post,
  data:yourdata,
  success:function(msg){
      //here is the function dealing with infomation form server.
  }
});

Solution 3:

The easiest way to get information from PHP to JavaScript via AJAX is to encode any PHP data as JSON using json_encode().

Here's a brief example, assuming your server errors are catchable

<?php
try {
    // process $_POST data
    // zip files, etc
    echo json_encode(array('status' => true));
} catch (Exception $e) {
    $data = array(
        'status'  => false,
        'message' => $e->getMessage()
    );
    echo json_encode($data);
}

Then, your jQuery code might look something like this

$('form').submit(function() {
    var data = $(this).serialize();
    $.ajax(this.action, {
        data: data,
        type: 'POST',
        dataType: 'json',
        success: function(data, textStatus, jqXHR) {
            if (!data.status) {
                alert(data.message);
                return;
            }
            // otherwise, everything worked ok
        },
        error: error(jqXHR, textStatus, errorThrown) {
            // handle HTTP errors here
        }
    });
    return false;
});

Post a Comment for "Some Ajax Help?"