get specific array keys back in javascript ajax request - javascript

I've got the following ajax request that I want to run every 5 seconds. To test it, I just set up a couple alerts. I set up an alert('hello'); inside the success and it fired every 5 seconds. So that works.
What isnt working is the if(response.update==true){ section.
I am setting
<?php $data['update'] = "true"; return $data; ?> inside the ajax url file.
Am I doing something wrong? Is this an incorrect approach? Am I missing something?
I even tried setting datatype: json, inside ajax and returning return json_encode($data); inside ajax url as well with no success.
CODE
<script type="text/javascript">
$(document).ready(function(){
/* AJAX request to checker */
setInterval(
function (){
$.ajax({
type: 'POST',
url: '<?php echo http() . $websitedomain .'/Manage/order_management/search_orders_checker.php'; ?>',
datatype: html,
data: { counter:10 },
success: function(response){
if(response.update==true){
alert('yes');
}
}
})
},5000);
});
</script>
EDIT
console log is now reporting the json response. But the if (response.update == "true") { alert('yes'); } still isnt working.
The console.log response: {"update":"true"} and its updating every 5 seconds like its supposed to.

Here are all the things you need to get it working:
1) PHP:
you need to
encode your data as JSON
echo your data to your script's output, rather then returning it somewhere within PHP
return a boolean true instead of a string "true" in the "update" field
Here's the new code for that:
<?php
$data['update'] = true;
echo json_encode($data);
?>
2) JavaScript:
You need to change datatype: html to dataType: "json"
This is because
JS variables are case-sensitive, so jQuery doesn't recognise an
option called 'datatype'
the value "json" must be string (before you used html which was actually a reference to a non-existent variable
specifying "json" tells jQuery to automatically parse the response as JSON, meaning you don't have to do you own call to JSON.parse()
in the callback.

Couple things look incorrect here. First off...
<?php $data['update'] = "true"; return $data; ?>
If this is how you are returning your data, then this is not returning json. You need to encode the associative array into json and echo that to the standard out.
<?php $data['update'] = "true"; echo json_encode($data); ?>
Once you have that, then you can make your ajax request expect the response to be json.
$.ajax({
type: 'POST',
url: '<?php echo http() . $websitedomain .'/Manage/order_management/search_orders_checker.php'; ?>',
//dataType tells ajax to auto-parse the json response into an object
dataType: 'json',
data: { counter:10 },
success: function(response){
if(response.update==true){
alert('yes');
}
}
})

Related

Run php script inside JavaScript at regular intervals using ajax or any method

I have a index.php with a javascript function Loaddata()
function loaddata(){
<?php
$data = //connects to database and gives new data
?>
var data = <?php echo json_encode($data); ?>;
}
setInterval(loaddata,3000);
I understand the fact that php scripts can only be run once when the page is loaded and it cannot be run again using set interval method. Can someone please guide me how to run the php script at regular intervals inside my index.php using ajax or some other method. My javascript variable "data" depends upon the php script to gets its value. Thanks a lot
Generally, using ajax to get data from a PHP page on the front page is a good way. The way you write this code is fine, too. I suggest writing like this,
var data = <?php echo json_encode($data);?>;
function loaddata(){
// use data
}
setInterval(loaddata,3000);
I think it is more clear
You could use an ajax call to retrive data from php and call that function in setInterval function something like this.
function demofunc()
{
$.ajax({
url: '<?php echo base_url();?>',
type: 'POST',
data: formdata,
dataType: 'json',
success: function(data) {
// do your thing
}
});
}
setInterval(demofunc,3000);
If anyone wondering how to do it.
Echo the PHP value that you want ajax to get for you.
Do an ajax request to the php page to get the data.
$.ajax({
method: 'get',
url: 'time.php',
data: {
'ajax': true
},
success: function(data) {
console.log(data)
}
});
// Second Method
$.get('time.php',function(data){
console.log(data);
});
PHP file
if ($_GET['ajax']) {
echo "HELOOO";
}
//if using the 2nd method just echo
echo "hi second method";

Send array with Ajax to PHP script in wordpress

I'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress.
Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
Send array with Ajax to PHP script
Passing JavaScript array to PHP through jQuery $.ajax
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps

Read PHP output from array with AJAX

My PHP is outputting data like this:
$data['full_feed'] = $sxml;
$data['other_stuff']= $new;
echo json_encode($data);
So, in my jQuery, I'm doing this.
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
console.log(data['full_feed']);
});
This comes back undefined. So does console.log(data.full_feed). I'm getting back from PHP a valid JSON object, but missing how I can "parse" it correctly.
Parse "data" parameter in response with jQuery.parseJSON function. Then use parsed.full_feed value. Like below:
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
data = jQuery.parseJSON(data);
console.log(data.full_feed);
});
You can do like #tilz0R said or for your example to work you need to tell the browser you are sending a json response. So need to set content type header like
header('Content-Type: application/json');
echo json_encode($data);
to see what the server is returning do console.log(typeof data). If its a string you need to parse it. if its an object, it is already parsed.
Also you can put dataType:'json' in your ajax call to let jquery know you are excepting a json response.

Extract Json response

I am trying to to extract a Json response in jquery sent from a php file.
This is the .js code:
$.ajax({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
datatype: 'json',
data: {'userCheck': username},
success: function(data){
// Check if username is available or not
},
error: function(){
alert('Much wrong, such sad');
}
});
This is the response from the php file:
if($sth->fetchColumn()!=0){
//$response = array("taken");
$response = array("username"=>"taken");
echo json_encode($response);
//echo '{"username':'taken"}';
}else{
//$response = array("available");
$response = array("username"=>"available");
echo json_encode($response);
//echo '{"username":"available"}';
}
I have tried all combinations I can think of in both files, but nothing seems to work. It is a simple check for a username in the database. If I console log the data I get from the response, I get this:
{"username":"available"}<!DOCTYPE html>
// The rest of the page html
So the info is there, but how do I access it? I have tried several syntaxes found around the internet, but no luck so far. I seem to recall that a json response only can contain valid json, so is the problem the html? I don't think I can avoid this due to the structure of my application, so hopefully it is possible to access the json with my present structure.
in you Ajax
EDIT:
change
datatype:"json",
the case of parameter name was not respected, the t must be T
dataType:"json",
now retry please
$.ajax
({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
dataType: 'json',
data: {'userCheck': username},
success: function(data)
{
// Check if username is available or not
switch(data.username)
{
case "available":
// do you want
break;
case "taken":
// do you want
break;
}
},
error: function()
{
alert('Much wrong, such sad');
}
});
in PHP
simply that, and don't forget to exit; to avoid include html page in your json response !
This is the code coming after the }".... who break your json output
and make it unreadable by javascript (worste, it simply break your javascript !)
echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
When you're responding to an AJAX call, you should just return the JSON response, not the HTML of the page. Add:
exit();
after this code so you don't display the HTML after the JSON.
In the JS code, use if (data.username == 'available') to tell whether the username is available.
The other problem in your code is that you have a typo here:
datatype: 'json',
It should be dataType, with an uppercase T.
You can also put:
header("Content-type: application/json");
before echoing the JSON in the script, and jQuery will automatically parse the response.
Also you can set request headers in your jQuery ajax call beforeSend function like follows
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Accept', 'application/json');
}
So you're strictly declaring the data type to be json

Returning a json array using AJAX

Here's the javascript:
var data = $('form#registration-form').serialize();
$.post(
'<?php echo $this->url('/register', 'do_register')?>',
function(data) {
alert(data);
},
'json'
);
And here's the ending of the do_register() method:
if( $_REQUEST['format']=='JSON' ){
$jsonHelper=Loader::helper('json');
echo $jsonHelper->encode($registerData);
die;
}
The $registerData variable holds all the data I need. I want the function to return it after the ajax call. However, when I specify dataType: 'json' nothing is returned. Any suggestions?
I think your problem is in url
$.post(
'<?php echo $this->url("/register", "do_register"); ?>?format=JSON',
function(data) {
alert(data);
},
'json'
);
Also you can use following line in php part to get json values
header('Content-Type: application/json');
I suppose problem is somewhere here:
'<?php echo $this->url('/register', 'do_register')?>', in using quotes.
Use double and single quotes:
"<?php echo $this->url('/register', 'do_register')?>",.
It's impossible to receive right suggestion with little description.
Y'd better to paste more php & javascript code, with much more context, thing to be simple.
And another suggestion, mixed coding is bad. separating the javascript and php with php template such as Smarty.
var data = $('form#registration-form').serialize();
$.post(
'<?php echo $this->url('/register', 'do_register')?>',
function(data) {
alert(data);
},
'json'
);
this source file of above code is a php file ?
Debug with firebug to capture weather the ajax request sent or not
Why use JSON helper??
json_decode(string $json);
json_encode(mixed $value); //normally array...
it is built-in in php.

Categories