Ajax store response json in variables - php

The response of success ajax call is in the form of json like this one:
{"prize_name":"Keys 4","prize_image":"http:\/\/localhost\/web-game-w\/wp-content\/uploads\/2017\/09\/4rare.jpg"}
How I can store "prize_name" & "prize_image" in variables for later use?
Here is the ajax code:
$("#ajax").click(function(e){
e.preventDefault();
var data = {
'action': 'getprize_data',
dataType: "json",
async: false
};
$.post(ajaxurl, data, function(response) {
console.log(response);
// Store vars
});
});
Also I have an issue. This response.prize_name will return error response.prize_name is undefined.

declare those variables without using var before the ajax call starts and assign the values to those variables in the success function
prize_name = prize_image = "";
$("#ajax").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxurl, // give url over here
data: {action: 'getprize_data'},
dataType: 'json',
async: false // always avoid false if you can
success: function(response) {
console.log(response);
response = JSON.parse(reponse);
// Store vars
// assign the values over here
// maybe you will need to decode the json
// if you are encoding it so use JSON.parse
// for decoding the json
},
});
});
Now the reason why I'm saying to declare variable without using var is because
If you don't use var , the variable bubbles up through the layers of
scope until it encounters a variable by the given name or the global
object (window, if you are doing it in the browser), where it then
attaches.

Your post call is wrong. I'd suggest to avoid async to false. But, if you need at all cost such a behavious you can rewrite your post as:
$.ajax({
type: "POST",
url: ajaxurl,
data: {action: 'getprize_data'},
success: function(response) {
......
},
dataType: 'json',
async: false
});
Instead to create global variables you can take advantage of data attributes.
You can store the values in this way:
$('#ajax').data('prizeName', response.prize_name);
And, in future, when you need such a value you can simply get the value with:
$('#ajax').data('prizeName');
Remember that ajax is asynchronous so the value will be available only when the succes callback will be executed. Hence, I suggest to use a callback function in your ajax success function.

Related

Using AJAX to pass variable to PHP and retrieve those using AJAX again

I want to pass values to a PHP script so i am using AJAX to pass those, and in the same function I am using another AJAX to retrieve those values.
The problem is that the second AJAX is not retrieving any value from the PHP file. Why is this? How can I store the variable passed on to the PHP script so that the second AJAX can retrieve it?
My code is as follows:
AJAX CODE:
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
PHP CODE:
<?php
$userAnswer = $_POST['name'];
echo json_encode($userAnswer);
?>
Use dataType:"json" for json data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.
SO, I recommend using one AJAX call and get the value with success.
example: in first ajax call
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
alert(data);
//or if the data is JSON
var jdata = jQuery.parseJSON(data);
}
});
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call
In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.
Try this: var_dump($_REQUEST); and check if you're receiving the values.
you have to pass values with the single quotes
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: '145'}), //variables should be pass like this
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
try it it may work.......

AJAX jQuery PHP Return Value

I am new to AJAX and am kind of confused by what PHP passes back to the jQuery.
So you have an AJAX function like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
(I took this from ajax another StackOverflow page.)
But on various other resources they will have the success section look like this:
success: function(data) {functionfoocommandshere}
I am just confused as to what dictates the naming of this variable? If the PHP ultimately echoes an array:
echo $myVar;
How can I get this from the AJAX?
An Ajax-Requests fetches a whole site. So you'll not get any data in variables, but the whole site in the data-parameter. All echos you made together will be in this parameter. If you want to retrieve an array, you should transform it to json before.
echo json_encode($myArray);
Then you can receive it via Ajax in this way
$.ajax({ url: '/my/site',
data: {action: 'test'},
dataType: 'json',
type: 'post',
success: function(output) {
alert(output);
}
});
In you PHP file, use json_encode to turn the array into a more convenient format for use in Javascript. So you would have something like:
echo json_encode($myArray);
Then, in your JavaScript, the data variable of the success method will hold the JSON. Use jQuery's parseJSON to convert this to a JavaScript object, which will then be very easy to manipulate. I don't know what you array contains, but you might do something like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.name[0] === "John");
}
});
Again, the data variable here will contain anything your PHP outputs, but JSON is a common and convenient way to transfer data back to your JavaScript.
<script type="text/javascript">
$.ajax({
url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
</script>
<?php
$action = $_POST['action'];
echo $action;?>
Any output that is printed/echoed will be returned to the success function. This is handy when you want to fill an html container with something that you need to run in real time.
Once you get the hang of this, another option is to use JSON to return variables with values.
The data that's returned from the PHP AJAX function, can be retrieved from the success block. Here's the manual
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
dataType: 'json',
success: function(output) {
//output is the data returned from PHP AJAX function in JSON format
alert(output);
}
});

How to return a value to javascript after posting via ajax (Jquery)

I'm sending data via ajax (jquery) to php where it will be processed. I'd like to return a value from the php script, but I'm not sure how.
How do I return the result back?
$(document).ready(function() { //This script sends var Score to php
Score=100; //Dummy variable
$.ajax({
type: "POST",
url: "returnresults.php",
data: { 'Score':Score },
success: function(){
$('#box2').html(Score);
}
})
});
Very simple PHP CODE
<?php
$Score=$_POST['Score'];
if (isset($_POST['Score'])) {
$Score=80;
}
?>
Your PHP page should output the html or text that you want returned, so at its simplest perhaps add this to the end of your PHP:
echo $Score;
If you want to pre-format it a bit within your PHP then:
echo "<div>" . $Score . "</div>";
Where you can make the html markup as simple or complicated as appropriate (the <div> in this case being just an example, obviously).
Then your jQuery ajax call will automatically pass the response through as a parameter to your success handler, so:
$.ajax({
type: "POST",
url: "returnresults.php",
data: { 'Score':Score },
success: function(data){ // <-- note the parameter here, not in your code
$('#box2').html(data);
}
});
(data will be the response).
Note: if you know that the only thing you want to do with the response from the ajax call is to take the data/text/html and put it into a particular element you can simplify things by just using the jquery .load() method instead of $.ajax():
$('#box2').load("returnresults.php", { 'Score':Score });
Check the documentation. In particular with respect to the success handler function:
success(data, textStatus, jqXHR)
A function to be
called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object.
So jQuery will pass three parameters to your success function. The first one contains the data that you want. If you just want to pass exactly what the server returns on into your success handler, you can do:
$(document).ready(function() { //This script sends var Score to php
$.ajax({
type: "POST",
url: "returnresults.php",
data: { 'Score':Score },
dataType: "text", //set the dataType to 'text' so that jQuery passes it verbatim
success: function(newScore){ //the first parameter will contain the response the server sent, we ignore the other two parameters in this example
$('#box2').html(newScore);
}
})
});
And then in your PHP code, just write the desired value straight to the response.
$(document).ready(function() { //This script sends var Score to php
Score=100; //Dummy variable
$.ajax({
type: "POST",
url: "returnresults.php",
data: { 'Score':Score },
success: function(response){
alert(response);
$('#box2').html(Score);
}
})
});

jQuery - now: Creating an object and storing values in it to pass to an AJAX call

I have an array:
myarr = [];
I'm filling it with some values:
myarray['name'] = "Me!";
Now I want to transform that array into a set of Key => Value pairs. I though jQuery would do it automatically, but it doesn't seem to.
$.ajax
({
type: "POST",
dataType: "text",
url: "myurl",
data: myarr
});
Is there a way to do this or something I'm doing wrong? I get no javascript errors, and no serverside errors other then no POST information at all.
I need the request to be sent as a true POST request. I need to keep the php code simple because sometimes the login won't be an AJAX call.
I'm now trying the following with an error unexepected token ':'
myarr:
{
'name':'me'
}
The question has now become: How do I initialize a new javascript object as "blank", how do I set up mappings, and how do I pass it in an AJAX call?
The data attribute is an object, so it uses notation like so:
data: { 'Name': 'Me!' }
Not
data: ['Name':'Me!']
You need to convert your array to an object. You can easily do this in place of an array:
myData.Name = 'Me';
myData.OtherProp = 'Something';
Here's some samples:
$.ajax({
type: 'POST',
dataType: 'text/html',
url: 'myUrl.php',
data:
{
'Name': 'Me!'
},
success: function(data, status)
{
// data is the returned response
}
});
OR
var myObject = new Object();
myObject.Name = 'Me!';
$.ajax({
type: 'POST',
dataType: 'text/html',
url: 'myUrl.php',
data: myObject
});
Both should get you to the right place.
You cannot pass the array directly, you need to encode it first and then pass it. For example you can use json2.js from json.org to encode it as JSON:
var mydata = JSON.stringify(myarr);
$.ajax
({
type: "POST",
dataType: "text",
url: "myurl",
data: {"mydata" : mydata}
});
Then you will need to use json_decode in PHP to convert the JSON string back to an array.
Update
To address your new questions:
How do I initialize a new javascript object as "blank"?
You can create a new object like so:
var myObj = {};
How do I set up mappings?
There are a couple different ways:
myObj.name = "Me!";
myObj['name'] = "Me!";
How do I pass it in an AJAX call?
Just pass it directly as the data argument:
data: myObj
Continue exactly like you have been, but change [ to { and ] to } (which changes your array to an object)

Can a Jquery Ajax Call Accept an Object on Succes from PHP?

I'm writing a simple ajax function and looking to populate two text input fields with the 'success' results. I'm wondering what my php syntax has to be to return an object.
Here is my Javascript function
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}
Here is my php doc (so far, this is where I need to know how to return an object)...
<?php
$data = array('title'=>'this');
echo json_encode($data);
When I run the function I just get the alert "undefined".
Suggestions?
Thanks,
-J
Try this. You can specify that you're expecting a JSON object and then you can interpret data accordingly.
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data.title);
}
});
}
I have returned JSON data from the server via a jQuery Ajax call, not in PHP but it should be the same. As long as you set the content-type of your response to application/json jQuery should consider the responseText as a JSON string. Alternatively you can also set dataType: "JSON" in your Ajax call which tells jQuery that you expect JSON.
Your php page returns: {"title":"this"} in this case.
So you can reference the result with:
alert(data.title);
You may need to specify the data type:
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
dataType: 'json',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}

Categories