I am sending a json string using JQuery.ajax to a php page where I am trying to pull the array and mediate through the variables. For some reason, I can see the POST in firebug when I run the script but I when I attempt to get the parameters all I get is an empty Array(). I have been trying to figure this out for hours and am at my wits end. I moving from asp.net to .php so I am still a little fresh with my syntax, but this seems like it should be fairly simple.
Here is my code for the jquery send.
$('#form_add').submit(function() {
var serial_data = $(this).serialize();
$(".page_content").fadeOut("slow", function(){
$.get(uri_base +'/'+uri_cont+'/get_db_name/true/'+Math.random(), function(data) {
$.ajax({
type: 'POST',
url: uri_base +'/AJAX/add_record/'+data+'/'+Math.random(),
data: serial_data,
contentType: "application/json",
success: function(data){
$.ajax({
type: 'POST',
url: uri_base +"/"+ uri_cont +"/"+ uri_func,
data: data,
success: function(data){
alert(data)
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
});
});
return false;
});
Ignore the first .get(), that just pulls back a variable to complete the next URL. The first.ajax() call sends the serialized form data to my AJAX controller and pushes into the db. The return from the controller sends back an Array of Objects that I converted to json.
if(isset($key)){
$data['add_msg'] = $this->model_ajax->add_record($table,$array);
$exploded_data = json_encode($data['add_msg']);
print_r($exploded_data);
exit;
}
From there the next .ajax() is supposed to send the data to my controller to pull back a view to display in the .pag_content div. I have tried echoing the json object, a for each loop to pull the keys out, and a myriad of other things. nothing ... I get either a JSON Invalid error (when trying to decode it), Just "Array()" output, or nothing at all when looping through them.
This is the controller code and the POST output that I am seeing in firebug...
echo $_POST;
$array = $_POST;
echo $array;
foreach($_POST as $key){
echo $key;
}
exit;
[{"id":"29","datetime":"2011-03-23 12:10:25","full_name":"Leroy Brown","email_address":"test#testing.com","password":"asdf","id_group":"0","id_sites":"0","active":"0"}]
before you output anything in php make sure you send the right content-type. The frameworks like JQuery and mootools tend to filter (as they should) with Accept charsets (you can see that in firebug)
header("Content-Type: application/json");
// could also be text/json, check the accept headers in firebug depending on your framework
:)
Related
//MAKE AJAX CALL TO REPOPULATE TABLE
var newData = 'page_number=1&type=2';
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'http://www.myurl.net/form_validate.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
//REFORMAT UPON SUCCESSFUL AJAX CALL
alert(response);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
All I've put in my PHP file is:
<?php echo "test"; ?>
When I go straight to that file, it echoes 'test.' When I try to run the AJAX function on the click of a button it gives me the error:
[object Object] error
in an alert window. I've put the absolute URL to the file because I was thinking that the relative linking I was using was wrong but it now seems like it's some other issue. Am I overlooking a simple syntax error? Sorry if this is super basic but I can't seem to figure this out after working on it for a really long time. Thanks for your help.
The problem is your absolute url . Some browsers have problems dealing with absolute urls, consider it as a cross-domain request and block it even if it's not a cross-domain request. You should try with relative url instead
The problem might be in the url, try with relative path instead of absolute.
You named the file was in the same folder as the .js file, so try
url: '/directory_path_to_the_same_folder_as_the_JS_file/form_validate.php',
Try using done with jQuery.post instead.
For example:
jQuery.post('form_validate.php', data).done(
function(data, textStatus, jqXHR) {
alert(jqXHR.responseText);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
}).complete(function() {
// Common code when request completes
});
If your error is [object Object] error NOT FOUND then the reason is
the specified url in AJAX is not correct.
If your error is [object Object] error INTERNAL SERVER ERROR , its
because of the error in your server file ie the php file ,error like variables not defined correctly etc..
Some times error may occur due to cross domain, if you have not
specified headers when in case your php file is not in the same
domain
Hope this helps
Thank you
function abc(){
var ret=true;
$.ajax({
type: 'POST',
url: 'send_password.php',
data: 'mail_to=mymail&new_password=pwd',
async:false,
success: function(response){
},
error: function(r){
ret=false;
}
});
return ret;
}
alert(abc());
Have a look at this testfiddle
I've tried this many times now, using difference methods and none of them have worked for me, so I'm asking this question.
I have a small form that takes in 4 pieces of information, a persons title, first name, middle name and last name. When I hit a button, a JSON Object is formed, and sent as post data through a jQuery.ajax method.
JSON Sent to PHP file:
{
"title": "Mr",
"firstName":"Banana",
"middleName":"Slippy",
"lastName":"McDougle"
}
Ajax call on button press:
function insertPerson(obj, callback){
$.ajax({
type: "POST",
data: "json=" + JSON.stringify(obj),
url: "insertData.php",
success: function(obj){
if (callback){ callback(obj) };
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
}
I pass in a Javascript Object that is then stringyfied and posted as a parameter name 'json'.
In my php file I assign the posted string to a variable, name $json, I then decode using json_decode(), do some funky business, and send a response back to the browser.
insertData.php:
require ('connect.php');
header('Content-type: application/json');
$json_string = $_POST['json'];
$json = json_decode($json_string);
...do server related inserts/selects etc...
echo json_encode($json->title);
At the moment I just want to return the title property of the json object that was sent in the post request, but anything I return comes back as null. If I echo back the string, without decoding it, then I get the following:
{\"title\":\"Mr\",\"firstName\":\"Banana\",\"middleName\":\"Slippy\",\"lastName\":\"McDougle\"}
If I try to extract values using:
$title = $json->title;
and put that into a MYSQL statement, it's inserted as null or blank, nothing gets input.
Am I doing something wrong? Or have I somehow got an outdated version of PHP to handle JSON? And help is greatly appreciated.
Why do you want to send JSON to the PHP script? What's wrong with using a query string?
$.ajax({
type: "POST",
data: obj,
url: "insertData.php",
success: function(obj){
if (callback){ callback(obj) };
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
This will convert obj to a query string, and then you can just do $_POST['firstName'] and $_POST['lastName'].
I think this is the best shot for you.
jQuery Ajax POST example with PHP
My AJAX request to pings the server, and the URL but returns an error because it doesnt like the '<' as the open tag for the php script.
AJAX script.
$.ajax({
url: "data.php",
type: "POST",
data: JSON.stringify({"data":transaction}),
dataType: "json",
success: function(data, textStatus, jqXHR){
alert("success");
currentProcesses -= 1;
$("<span>").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
},
error: function(jqXHR, textStatus, errorThrown){
alert("error with ajax call "+textStatus+" "+errorThrown);
}
});
php script
<?php
$win = $_POST['data'];
?>
Am I using the wrong flag settings for the AJAX call?
The body of your POST request is encoded as application/json instead of application/x-www-form-urlencoded.
You aren't doing anything to make the request say that the data is encoded in JSON and you aren't doing anything in PHP to try to parse JSON.
As a result, PHP fails to populate $_POST, because the data is in the wrong format.
The solution is: Don't send JSON. Just give the data property an object as its value, and jQuery will serialise it to application/x-www-form-urlencoded data for you.
data: { "data": transaction },
(Assuming that transaction is not a complex data type (like an array or object).
Additionally, the body variable is undefined. You should either use a string (to make it a selector: "body") or pass the body element directly: document.body.
Is it choking on what it's receiveing? Try this...put an id attribute on your span tag, and reference that.
In the page:
<span id="someName">...</span>
In your ajax call:
$("#someName").html(...
Try making the span more unique using class or id like
<span id="output"></span>
and try this.
$("#output").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
}
I'm going crazy over this script, i'm trying to het this working by when some one click on a button then with ajax fetch data from another URL then fill form inputs with the fetched data can any one help please
my code look like this:
$(document).ready(function()
{
$("#getmetaData").click(function(){
var element = $(this);
var url = $("#url").val();
var dataString = 'url='+ url ;
//alert(dataString);
if(url=='http://')
{
alert("Please Enter URL to fetch Meta Data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loader.gif" >');
$.ajax({
type: "POST",
url: "fetch-metadata.php",
data: dataString,
cache: false,
success: function(data){
$("#title").val(data);
$("#description").val(data);
$("#keywords").val(data);
$("#flash").hide();
}
});
}
return false;});});
If you see no error, which I am guessing is the case, it means your request is failing. Since you have no error function, when your request fails, your jQuery code will do nothing.
Add something like this to your $.ajax object argument:
error: function(jqXHR, textStatus, errorThrown) {
// now you can set a breakpoint or log textstatus/errorThrown
},
As per HackedByChinese's answer I would add an error callback function.
Also, in your success callback function you are simply using the 'data' variable without doing anything with it. Depending on the format of the response from 'fetch-metadata.php' I think you'll need to do something first. It's either XML in which case you'll need to parse it. If its json you can use object dot notation to reference it's properties.
Lastly, I'd use something like Firebug to look at the request and response for this Ajax request to make sure it's being processed and not returning a 404 or 500. Assuming its returning a valid response, using Firebug you can look at the response to see the raw data that is being returned to your js.
Hope this helps
I have an AJAX request (using JQuery) that calls a PHP script which does some database business. The request code is as follows:
$.ajax({
url: "script.php",
data: { value: value
},
type: 'post',
success: function(output){
alert(output);
}
});
However, I wanted to see if there was a way to also (in addition to the unchanged output string) return a status. It can be as simple as an integer. The point is I want to disable a button (with Javascript) if the PHP script for any reason fails to connect to mySQL, but I still want the PHP scripts output exactly as it would be.
I tried the error option:
...
success: function(output){
alert(output);
},
error: function(output){
// do something
}
but I do not know how to make PHP display an error and continue on the rest of the script. Again, I don't want to tamper at all with the output string.
In pseudo-code, I'm looking for something like this:
$.ajax({
url: "script.php",
data: { value: value
},
type: 'post',
success: function(output){
if(output.status == 0){
alert(output);
}else{
// do something else
}
}
});
Is anything of the sort possible? Thanks for any and all help!
I usually return data from the server in JSON format. This way I can return as many different types of data as may be needed by the success function in javascript.
basically in PHP you would do something like
$response = new stdClass();
$response->error = 'Could not connect to Mysql';
$response->message = 'Some other text';
echo json_encode($response);
in JQuery, the ajax() method would automatically detect that the response is json and parse it into a javascript object, so you could access like this
if (typeof response.error !== undefined) alert(response.error);
for more on that look at dataType argument for the ajax() method in the jQuery documentation.
Yes. You can use HTTP status codes:
header('HTTP/1.1 500 Internal Server Error');
And use jQuery's statusCode property for jQuery.ajax():
$.ajax({
// stuff
statusCode: {
500: function(data) {
alert('Something went wrong!');
}
}
});
If your needs extend beyond what HTTP can offer, you can just return a status code within your data and process it in the success function, switching on data.status.
If I haven't misunderstood your question...
What I usually do is set the datatype of the AJAX call to 'xml' and output an xml from my PHP script. So I get multiple values in result. I usually make these attribute values.
<result status="success" something="etc" />
// vs.
<result status="failure" error="1" />
// consider 1 as the DB error
With this approach you might need to use the # tags in some PHP functions to prevent outputting the default errors.