Returning a json array using AJAX - javascript

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.

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";

get specific array keys back in javascript ajax request

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');
}
}
})

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

PHP JSON Encoded Object causes Ajax Error

This has been bugging me for the last few hours, and I've tried various searches but never found exactly this issue with an answer. Maybe asking and showing some code will help me get this figured out.
I am using ajax to do a post to PHP, which I want to just give a notification so that I may update a div on the page. In this case, I just need the PHP to say something like "Cfail" which the javascript would use to update page content.
Originally, I was going to try just text responses. So, my PHP for example would be like this:
<?php
session_start(); //Because have an encoded captcha answer.
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
echo 'Cfail';
}
?>
The Javascript would be:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'text',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned=='Cfail'){
alert("I read it right!");
}
}
});
});
});
It would run through the script just fine, but the result never would be what I was asking for. Alert showed the corrct text, however, research indicated that the issue with this was PHP apparently adding white space. The common answer was the encode a JSON response instead. So, I tried that.
Updated PHP:
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
$result = array('result' => 'Cfail');
echo json_encode($result);
exit;
}
?>
Updated Javascript:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'json',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
}
});
});
});
Which now no longer runs successfully. The alert doesn't come up, and the loader object remains visible(indicating the success never goes through). I tried putting an error section to the ajax, and it indeed fired that. However, I had no idea how to parse or even figure out what the error was exactly. The most I got in trying to get it was what PHP was outputting, which was {"result":"Cfail"} .... Which is what I would EXPECT PHP to give me.
I can work around this, I've done a similar set-up with just echoing a number instead of words and it used to work just fine as far as I knew. I'd just like to figure out what I am doing wrong here.
EDIT:
I managed to figure out what the issue was in my case. I had a require('config.php'); between the session start and the json_encode if statement. For some reason having the external file added, which was just me setting a couple variables for the code further down, some hidden character was added before the first { of the JSON object.
No idea why. As I said, it was just a $var='stuff'; situation in the require, but apparently it caused the issues. :/
Use this like
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
//$result = array('result' => 'Cfail');
$data['result'] = 'Cfail';
echo json_encode($data);
exit;
}
?>
This works for your javascript
use the below code, in your success call back, first parse the encoded json object that you are recieving from the back end and access the object property result to check it's value
success: function(returned){
returned = JSON.parse(returned);
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}

pass javascript variable to php mysql select query

I am running a mysql select query in php like this
<?php
$getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
$result=mysql_query($getvalue) or die(mysql_error());
while($row=mysql_fetch_array($result)){
extract($row);
echo $name;
}
?>
var1 and var2 are javascript variables on the same page. I know client side variable cannot be passed to server side. But is there any workaround as the variables are in the same page.
In order for you to make this happen - I believe - you have to use AJAX.
The code will look like this:
$.ajax({
url: 'your_script.php',
type: 'POST',
data: {var1: javascript_var_1, var2: javascript_var_2},
success: function(data) {
console.log("success");
}
});
Your PHP will look similar to this (without keeping in mind the JSON encode:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
$result=mysql_query($getvalue) or die(mysql_error());
while($row=mysql_fetch_array($result)){
extract($row);
echo $name;
}
?>
Then you can JSON encode the results and pretty much output them on the success. Your php script - however - must live on another php file.
Also, escape your data. Use prepared statements.
In theory, you could pass the vars to php via some sort of ajax call. I think it would go something like...
JavaScript:
var data = {
'var1': $('selector').val(),
'var2': $('selector').val()
};
$.ajax({
type: 'post',
url: 'path-to-your-file.php',
data: data,
timeout: 50000
}).done(function(response) {
console.log(response);
}).fail(function(error) {
// uh-oh.
});
php:
<?php
print_r($_POST['data']);
Otherwise, you could use:
cookie
hidden input
php:
<?php
... column1='$_COOKIE["mycookie1"]' and column2='$_COOKIE["mycookie1"]'";
... column1='$_POST["hidden1"]' and column2='$_POST["hidden2"]'";
NOTE: you will want to sanitize the data. Using raw cookie and/or input values could lead to some less than desirable results.
Use Method Post in AJAX or Form!! To send js variable in Php and receive it in php using $_post[ name_of_obj ];

Categories