Jquery Ajax call and simple PHP json string echo server - php

My PHP code on Xampp
<?php
$data = ((**Refer the JS fiddle Link below for JSON data**));
//header('Content-Type: application/json');
echo $data;
?>
my client Javascript code
function clickbtn(){
$.ajax({
url: 'http://localhost/json/index.php',
type: 'GET',
contentType:'json',
//data: JSON.stringify(data),
success:function(dataF){
console.log('SuccessMsg:'+dataF);
alert(dataF.surveyId);
},
error:function(){
alert('Error: Unable to connect to the server');
}
});
}
I am able to dump the JSON from the php server on my browser console. But i am unable to see the alert "SurveyID" value on alert box.
Kindly take the JSON data available in JS fiddle link and paste it in your PHP script and test it.
If you are testing on chrome Please add the ((Chrome installation path))--disable-web-security to allow cross domain origin policy and then run the JSfiddle link at your end.
JSfiddle for client JS and PHP JSON data

You should use the dataType option instead of contentType if you need the response to be JSON parsed automatically by jQuery.
$.ajax({
url: 'http://localhost/json/index.php',
type: 'GET',
dataType:'json', /* dataType instead of contentType */
...
success:function(dataF){
console.log('SuccessMsg:'+dataF);
alert(dataF.surveyId);
},
...
});

Sometimes jQuery (or the browser?) respone with a string instead of an object.
You have to ckeck this an parse it to json maybe. I've encountered this problem too often, so i' checking this every time.
function clickbtn(){
$.ajax({
url: 'http://localhost/json/index.php',
type: 'GET',
success:function(dataF){
console.log('SuccessMsg:'+dataF);
if(typeof dataF != 'object')
{
dataF = jQuery.parseJSON(dataF);
}
alert(dataF.surveyId);
},
error:function(){
alert('Error: Unable to connect to the server');
}
});
}
I think that the dataType parameter is sometimes ignored :(

Related

jQuery Ajax(post), data not being received by PHP

The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}

getting a json string in php from jquery ajax post

I am tring to write a page, which takes a RSS feed from a news site via AJAX and then sends it to PHP where I can work with it. The news feed is returned as an object array. I have tried posting it as it is, and also as a json string. The post method seems to be a success, but PHP gives an undefined index notice. This is my first time using AJAX and PHP and I seem to have problem with getting the data from the PHP side.
The error:
Notice: Undefined index: data in ...\index.php on line 33
Current code is the following:
ajax side
url = 'http://feeds.bbci.co.uk/news/rss.xml?edition=int';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('LOAD ERROR, INVALID URL');
},
success: function(xml){
values = xml.responseData.feed.entries;
var senddata = JSON.stringify(values);
console.log(senddata);
$.ajax({
type: "POST",
url: "index.php",
data: {data : senddata},
success: function(){
alert("postdone!");
},
error: function(){
alert("posterror!")
}
});
}
});
php side
<?php
$data = json_decode(stripslashes($_POST['data']));
echo $data;
?>
Wrap your code in an if to avoid that warning:
if (isset($_POST['data'])) {
$data = json_decode(stripslashes($_POST['data']));
echo $data;
}
The problem is when you visit that index.php from browser, there is no POST request, so of course $_POST is empty and $_POST['data'] is not set.
Hope you get the point.
EDIT:
Hmm I can't see anything seriously wrong. And actually now I recommend you to use php.net/manual/en/book.curl.php to get the data directly from the RSS, instead of nesting 2 ajax calls.

JQuery AJAX Issue without error

So I am adding a list of stores to a web page via a jQuery AJAX request. This little utility is not dynamic, just database driven. I have decided to use jQuery/AJAX to transfer the data because when I try to embed PHP in our current PHP CMS, I get a bunch of conflicting errors.
The problem I am having is that I am getting a jQuery AJAX error when trying to make the request to the PHP script, and I am not sure why.
Here is my AJAX request
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(data) {
console.log(data.error);
}
});
});
The cryptic console error i am getting is this
function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
Here is my PHP code if it will be helpful:
//database connection
$return_arr = array();
$sql = mysql_query("SELECT * FROM where_to_buy");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$row_array['store_name'] = $row['store_name'];
$row_array['store_url'] = $row['store_url'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
I think the problem might be because I wrapping my JSON in an array?
EDIT:: JSON output from php script as requested
[{"store_name":"Example 1","store_url":"http:\/\/www.example1.com"},{"store_name":"Example 2","store_url":"http:\/\/www.example2.com"}]
Thanks for any help!
The reason you are getting that weird error message is that the error callback for the jQuery ajax function takes 3 arguments instead of 1, as described in the docs here: http://api.jquery.com/jQuery.ajax/
The first argument is a jQuery-special XMLHttpRequest object, which has a property called error that contains the function you are seeing logged to your console. The actual error that occurred during execution of your ajax call is the passed in to the error callback as the 3rd argument.
To see it, you should do something like:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
That will get you closer to the real problem.
UPDATE:
Please show the output from your php script. It may be that it is not returning valid json. As noted in the php docs ( http://php.net/manual/en/function.json-encode.php ), [json_encode] only works with UTF-8 encoded data.
You might also check in to json_last_error ( http://php.net/manual/en/function.json-last-error.php ) to see if the encoding failed for some reason.
UPDATE 3:
It seems like your problem may be the path to the php script.
try it with:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php", // <-- notice the leading slash!!!
//dataType: "json",
success:function(data){
//results(data);
console.log(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
or, putting it all back together if the above logs the correct json output to the console...
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});

Jquery ajax request showing a old response

Hi I have a jQuery ajax request for a login system. At first, it worked very well. But after a few try, it just started to show negative response. I checked firebug and it says that the response is, in my case "Connected". But the ajax response just shows "Not_connected". I don't know what to do :(. Please help me.
This is my jquery code :
var data_str = "username="+usrn+"&password="+pwd;
$.ajax({
type: "POST",
url: "index.php?rnd=" + Math.random(),
data : data_str,
complete : function(xhr,data){
if(data == 'connected'){window.location.href = 'admin.php';}
else if(data = 'not_connected'){ error_gen.html('Invalid username or password'); }
alert(data);
}
});
AS for the PHP code :
$log_result = $u_obj->login_user();
if($log_result == true)/*user is connected*/
{
echo 'connected';
exit;/*stoping the script after sending the result*/
}
elseif($log_result == false)/*error while logging in*/
{
echo 'not_connected';
exit;/*stoping the script after sending the result*/
}
Look at this thread: Is it possible to cache POST methods in HTTP?
It might be that there are headers which now make browser caching the response (although it's POST).
Also instead of rnd=" + Math.random() you can add write
$.ajax({
type: "POST",
cache: false,
..
Could it be browser caching?
Try adding this $.ajaxSetup({ cache: false });
You are using the wrong $.ajax option to retrieve the result. You should use the success option. Just change the
complete : function(xhr,data){
line for
success : function(data){
It should work.

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

Categories