How to select the result from data success of ajax? - php

These are my code:
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
$("#myModalLabel").html(data);
}
});
stay.preventDefault();
});
And the success data result below:
$result1 = "code is invalid";
$result2 = "promo unavailable";
How can I select these and retrieve it?
This is what I did below but now working.
$("#myModalLabel").html(data->result1);

JavaScript uses dot syntax for accessing object properties, so...
$("#myModalLabel").html(data.result1);
I'll also add that you want to make sure the page at promo/code_validate prints out a JSON response, as that is how data will become an object ($.ajax is intelligent about how to parse the server's response, see the link below). So your code_validate page might look something like this:
{
"result1": "code is invalid",
"result2": "promo unavailable"
}
http://api.jquery.com/jquery.ajax/

Do this
Function controller
function code_validate()
{
echo json_encode(array('result1'=>'Code is invalid',
'result2'=>'Promo not available');
}
Javascript
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
var mydata = JSON.parse(data);
console.log(mydata.result1);
console.log(mydata.result1);
}
});
stay.preventDefault();
});
You must return it as JSON.
Goodluck meyt

Vincent, add the dataType paramater to your ajax call, setting it to 'json'. Then just parse the response to convert it to an object so that you can access the variables easily, e.g.
in AJAX call:
dataType: "json"
in success function:
var obj = jquery.parseJSON(data);
console.log(obj);//echo the object to the console
console.log(obj.result1);//echo the result1 property only, for example

The simplest way to do what you want is create a php associative array of your values then json encode the array and echo the resulting string like this:
$response = ["result1"=>"code is invalid", "result2"=>"promo unavailable"];
echo json_encode($response);
Then on the client side, access them like this
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
$("#modal-1").html(data.result1);
$("#modal-2").html(data.result2);
}
});
stay.preventDefault();
});

Related

return json from php and handle

I get this from ajax call
{"id":"381120774951940096","time":"Posted 0 minutes and 51 seconds ago.",....
How can I add each of these into variable, id, time etc? data.id won't work, it says undef.
<script>
$(function() {
$.ajax({
type: "POST",
url: "start.php",
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
})
});
</script>
This is what I return from start.php
$return = array('id' => $info['id_str'] ,'time' => timeDiff(new DateTime($info['created_at'])), 'name' => $info['user']['name'], 'text' => $info['text'], 'image' => $picture, 'url' => "http://twitter.com/{$info['user']['screen_name']}");
print_r(json_encode($return));
EDIT
I had that print_r inside foreach loop and that was the issue. So I added another array and used echo json_decode($array,true) at the end of file.Writing this just in case, might help someone.
Cheers
First, in your PHP, change your line to:
echo json_encode($return, true);
That second parameter ensures that the JSON is interpretable as an associative array. Also, you should use echo instead of print_r when returning JSON; print_r can alter the formatting.
Next, use the following AJAX call:
$.ajax({
type: "POST",
url: "start.php",
dataType: "json", // Add this option.
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
})
The dataType: "json" option ensures that data will be parsed as a JSON object as soon as it's retrieved. So, data.id should be immediately available in your success callback function.
Hope this helps!
Firstly, you should use echo in the server script. print_r is mainly for debugging arrays.
Secondly, you should declare a dataType option for the ajax call:
$.ajax({
dataType: "json", // <-- here
type: "POST",
url: "start.php",
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
});
The way you have it now, I think you are getting a string response as data.
You can verify that with console.log(JSON.stringify(data));
You have to set dataType: 'json' in your ajax. This means that jQuery will parse the result as JSON for you.
Then parse the data,
data = $.parseJSON(data);
Then read var id = data.id;
Also, in your PHP, No need to use print_r(). Just use echo instead print_r().like:
echo json_encode($return);
You'll need to parse the JSON string into an object. You can use JSON.parse to do this.
// Your JSON string
var json_str = "{'id': 'foo', 'time': 'bar'}";
// We need to parse it, converting it into a JS object
var json_obj = JSON.parse(json_str);
// We can now interact with it
console.log(json_obj.id);
console.log(json_obj.time);
Alternatively, you can parse JSON using a built in jQuery function parseJSON().
jQuery also has a built in function for fetching JSON called getJSON(). If memory serves, this is just a shorthand for doing an .ajax() call and specifying a datatype of json. This will handle the above (parsing JSON) for you, and is the recommended solution.

Parsing PHP Json Object using jQuery.

I am using jQuery's AJAX functionality - and I get a response back just fine, but for some odd reason I cannot parse the information inside of it!
I am calling the following:
console.log(results);
console.log(results.data);
And what I get is:
{"data":[{"member":"asdfasdf","status":"Invalid Email"}]}
undefined
Here is my jQuery:
$.ajax({
type: "POST",
url: "<?php echo Uri::base();?>ajax/add_members/organization",
data: {
organization_id: <?php echo $organization->id;?>,
members: $('#members').val(),
position: $('#position').val()
}
}).done(function (results) {
// lets add them to the table
console.log(results);
console.log(results.data);
});
UPDATE: dataType: 'json', was required!
Just because you have retrieved the string successfully in results doesn't mean it is already an object. You need to parse the JSON string into an object (this can be done as a shortcut depending on your actual method of calling (i.e getJSON).
You might need to do something like this to actually get an object.
var obj = $.parseJSON(results);
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

Retrieve JSON Data with AJAX

Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}

jQuery ajax request with json response, how to?

I am sending an ajax request with two post values, the first is "action" which defines what actions my php script has to parse, the other is "id" which is the id of the user it has to parse the script for.
The server returns 6 values inside an array() and is then encoded to JSON with the PHP function: json_encode();
Some of my responses are HTML, but when I encode it to JSON, it escapes "/" so it becomes "\/"
How do I disable that?
Also when I don't know how to display this in jQuery when I get the server response, I just thought that putting it all into a div would just display the numbers and HTML codes I had requested, but it displays the array as it is encoded in PHP.
PHP
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo json_encode($response);
jQuery:
$.ajax({
type: "POST",
dataType: "json",
url: "main.php",
data: "action=loadall&id=" + id,
complete: function(data) {
$('#main').html(data.responseText);
}
});
How do I make this into working JSON?
You need to call the
$.parseJSON();
For example:
...
success: function(data){
var json = $.parseJSON(data); // create an object with the key of the array
alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
},
error: function(data){
var json = $.parseJSON(data);
alert(json.error);
} ...
see this in
http://api.jquery.com/jQuery.parseJSON/
if you still have the problem of slashes:
search for security.magicquotes.disabling.php
or:
function.stripslashes.php
Note:
This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.
Firstly, it will help if you set the headers of your PHP to serve JSON:
header('Content-type: application/json');
Secondly, it will help to adjust your ajax call:
$.ajax({
url: "main.php",
type: "POST",
dataType: "json",
data: {"action": "loadall", "id": id},
success: function(data){
console.log(data);
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.
NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).
Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode method. Try this.
PHP change
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string
JS (Change the dataType from json to html or just don't set it jQuery will figure it out)
$.ajax({
type: "POST",
dataType: "html",
url: "main.php",
data: "action=loadall&id=" + id,
success: function(response){
$('#main').html(response);
}
});
Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener
see https://github.com/ArtNazarov/LazyJs
Sorry for my bad English
Try this code. You don't require the parse function because your data type is JSON so it is return JSON object.
$.ajax({
url : base_url+"Login/submit",
type: "POST",
dataType: "json",
data : {
'username': username,
'password': password
},
success: function(data)
{
alert(data.status);
}
});

Jquery, reading JSON variables received from PHP

Sorry if this is basic, but I have been dealing with figuring this out all day and have gotten to where I can do everything I need with Jquery and cakephp (not sure if cakephp matters in this or if its same as any PHP), I want to return a variable from a cakephp function to jquery, I had read about how to do it, like here:
the cakephp:
$test[ 'mytest'] = $test;
echo json_encode($test);
and the jquery:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
}
});
I just can't figure out how to get one or more variables back into usable form within jquery, I just want the variable so I can do whatever else with it, I've been looking at what I can find through searching but its not making it fully clear to me.. thanks for any advice.
The JSON variables are in the data variable. In your case, it'll look like this:
var data = {
myTest: "Whatever you wrote here"
};
... so you can read it from data.myTest.
(Not sure whether it's relevant but you can remove the http://localhost/ part from the URL;
AJAX does not allow cross-domain requests anyway.)
Your variables are in data.
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
var values = eval( data ); //if you 100 % trust to your sources.
}
});
Basically data variable contain the json string. To parse it and convert it again to JSON, you have to do following:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
json = $.parseJSON(data);
alert(json.mytest);
}
I haven't test it but it should work this way.
Note that when you specify dataType "json" or use $.getJSON (instead of $.ajax) jQuery will apply $.parseJSON automatically.
So in the "success" callback you do not need to parse the response using parseJSON again:
success: function(data) {
alert(data.mytest);
}
In case of returning a JSON variable back to view files you can use javascript helper:
in your utilities controller:
function ajax_component_call_handler() {
$this->layout = 'ajax';
if( $this->RequestHandler->isAjax()) {
$foobar = array('Foo' => array('Bar'));
$this->set('data', $foobar);
}
}
and in your view/utilities/ajax_component_call_handler.ctp you can use:
if( isset($data) ) {
$javascript->object($data); //converts PHP var to JSON
}
So, when you reach the stage in your function:
success: function(data) {
console.log(data); //it will be a JSON object.
}
In this case you will variable type handling separated from controllers and view logic (what if you'll need something else then JSON)...

Categories