ajax array data undefined - php

I have this ajax function:
$(document).ready(function(){
setInterval(function() {
$.ajax({
url: 'php.php',
type: 'POST',
success: function(data){
if( data != "0" ) {
alert(data.a);
}
},
});
}, 5000);
});
and a PHP to return:
<?php
header('Content-type: application/json');
...some function
if($num>0){
echo json_encode(array("a" => "valueA", "b" => "valueB"));
}
else{
echo json_encode(0);
}
?>
when I have the alert message, it shows me "UNDEFINED" instead of "valueA".
Is something wrong with my array or ajax?

Set dataType: 'json' to your $.ajax call:
$.ajax({
url: 'php.php',
type: 'POST',
dataType: 'json',
success: ...
dataType allows you to define type of data returned from server. By default, there's intelligent quess and maybe that's not enough.

Related

is it possible to display only a particular echo response from server using ajax

I am trying to figure out how to just display a particular response from php using ajax for example. I have a php which gives the following response -
echo 'Success'; //Display only this
//Some other process
echo 'Something else for other process';
JS
$.ajax({
type: "POST",
url: "some.php",
data: {action: 'test'},
dataType:'JSON',
success: function(response){
$( '#name_status' ).html(response);
}
});
Use if else.
And while sending AJAX request, send conditional parameters.
For example, flag: set it to either yes or no.
Get these parameters $_POST ed in PHP back end.
Depending upon the value of AJAX sent parameter, print the response.
JS:
$.ajax({
type: "POST",
url: "some.php",
data: {action: 'test', 'flag' : 'yes'},
dataType:'JSON',
success: function(response){
$( '#name_status' ).html(response);
}
});
Set flag to yes or no // This is just sample.
In PHP,
if (isset($_POST['flag'] && $_POST['flag'] == 'yes') {
echo 'Success'; //Display only this
}
else {
echo 'Something else for other process';
}
You will have send json_encode to receive a JSON response and will have to accordingly change the PHP too. Below is the updated code that you can try:
PHP:
if($_POST['action'] == 'test') {
$returnArray = array('message' => 'Success');
} else {
$returnArray = array('message' => 'Something else for other process');
}
echo json_encode($returnArray);
JS
$.ajax({
type: "POST",
url: "some.php",
data: {
action: 'test'
},
dataType: 'JSON',
success: function(response) {
var responseObj = jQuery.parseJSON(response);
$('#name_status').html(responseObj.message);
}
});

Array object to php using ajax

How can i send data like this to php using ajax
["{"title":"mr","fname":"john","lname":"Annah","oname":"Clement","staffid":"123"}"]
try json_encode
for more refer -
http://php.net/manual/en/function.json-encode.php
Do it like so, using jQuery(which you need to include in your script):
<script>
var data={};
data= {
"title":"mr",
"fname":"john",
"lname":"Annah",
"oname":"Clement",
"staffid":"123"};
$.ajax({
url:"somwhere.php",
type:"POST",
dataType:"JSON",
data:data,
async: true});
</script>
And on the page where you want to catch this data, do it like this:
<?php
$title=$_POST['title'];
$fname=$_POST['fname'];
?>
And so on.
stringify before sending
Eg :
var postData = [
{ "id":"1", "name":"bob"},
{ "id":"2", "name":"jonas"}]
this works,
$.ajax({
url: Url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(postData) //stringify is important,
});
Try this
$(document).on("click", "#your element", function () {
$.ajax({
type: 'POST',
url: "your_url",
data : {"title":"mr","fname":"john","lname":"Annah","oname":"Clement","staffid":"123"},,
success: function (result) {
### your action after ajax
},
})
})
you can pass it in data like this,
$.ajax({
url: 'url',
type: 'GET',
data: { title:"mr",fname:"john",lname:"Annah",oname:"Clement",staffid:"123" } ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
//your success code
}
});

Simple ajax call in wordpress for upvoting post

Here's my ajax call:
$("#yes, #no").click(function(){
var upOrDown = $(this).attr('id');
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
action: "updateVote",
data: {upOrDown: upOrDown},
dataType: "json",
success: function(data) {
console.log(data.output);
}
});
return false;
});
Here's the function in functions.php
function updateVote() {
echo json_encode(array(
'output' => 'hello!'
));
die();
}
add_action('wp_ajax_updateVote', 'updateVote');
add_action('wp_ajax_nopriv_updateVote', 'updateVote');
Why does this keep returning "0". It should return "hello!"
Thanks.

jquery json request failed

I'm trying to make a json call with jquery but noting happened. My code:
javascript:
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
}
});
});
});
</script>
PHP
$output = array(
'percentage' => "50"
);
echo json_encode($output);
Any suggestions?
The code looks fine to me,
EDITED
Also try removing the protocol and use url: "//<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error: function (jqXHR,textStatus,errorThrown)
{
//Check for any error here
}
});
});
if you add and error callback to the ajax call you should get some error printouts to let you know what is going on
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error : function (e1, e2, e3) {
console.log(e1);
console.log(e2);
console.log(e3);
}
});
EDIT:
i just had a thought, if i remember correctly jquery ajax doesnt like using full url's if possible try using a relative path

ajax call php code in a file and get result

Some code I want to call from ajax is in a separate file.php:
<?php
session_start();
$email1 = $_POST['email1'];
//some code here processing $email1
$response = 'some text';
?>
This is how I call it from ajax:
$.ajax({ url: 'file.php',
data: {email1: $("#user_email").val()},
type: 'post'
});
I'd like to be able to do something like this after the call to file.php:
alert($response);
How do I do that?
In your PHP you have to echo the $response, and in your JS you have to specify the callback function like so:
$.ajax({
url: 'file.php',
data: {
email1: $("#user_email").val()
},
type: 'post',
success: function(data) {
alert(data);
}
});
Inside the ajax call, include a success.. ex:
success: function(data) {
alert(data);
},
This will pop an alert up with your response.
Try:
$.ajax({ url: 'file.php',
data: {email1: $("#user_email").val()},
type: 'post',
success: function(data) {
alert(data);
}
});
Check out the documentation
You also need to echo out the response in your PHP file:
echo $response;
Something like this?
$.ajax({
type: "POST",
url: "file.php",
data: {email1: $("#user_email").val()},
success: function(data) {
alert(data);
}
});

Categories