JQuery AJAX Issue without error - php

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

Related

php ajax display data from database in multiple textboxes

Every one am new to php and ajax.
Am writing a code to fetch data from mysql database
and display them in textboxes but is not working.
Here is my code.
I need your help please.
Thanks in advance
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box1').val(data);
$('#input-box2').val(data);
}
});
});
<input type="text" id="input-box1">
<input type="text" id="input-box2">
<button type="button" id="btn_get">Click</button>
//get data from db here
$textbox1 = 'foo';
$textbox2 = 'deen';
echo $textbox1;
echo $textbox2;
Here are some approaches, maybe them can help you:
The first approach would be to check your console to make sure that the jQuery version allows you to use the $.ajax() resource. Some jQuery versions like the "slim" doesn't provide ajax calls.
Once you have checked that put the property error within your ajax call:
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box1').val(data);
$('#input-box2').val(data);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
});
If you have a error response you will be able to identify it checking your browser's console tool (F12).
Check your /path/to/php/file to make sure that your file really exists.
Remember that the success callback gets your echo command as a string. So probably your return will be something like this:
foodeen
A good approach would be to return a json response:
$textbox1 = 'foo';
$textbox2 = 'deen';
echo json_encode(array($textbox1 ,"textBox1"));
Finally when your response is executed in the success callback you'll be able to convert it from plain string to a json format:
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
var response = JSON.stringify(data);
$('#input-box1').val(response[0]);
$('#input-box2').val(response[1]);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
});

how to pass JSON data to php using ajax post

Here is the code: (the #debug div text is shown below)
$("#debug").text(JSON.stringify(data));
// Try to save to a file
$.ajax({
type: 'POST',
url: './json.php',
dataType: 'json',
data: JSON.stringify(data),
success: function(xhr, status, errorMessage) {
if( xhr.responseText == "Success" ) {
alert("Success!");
} else {
alert("response was "+xhr.responseText);
}
},
error: function(xhr, status, errorMessage) {
$("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
}
});
The JSON.php page is:
<?php
openlog("scriptLog.txt", LOG_PID | LOG_PERROR, LOG_LOCAL0);
$json = $_POST['json'];
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
syslog(LOG_DEBUG, "Received Data");
if (json_decode($json) != null) { /* sanity check */
$file = fopen('./data.json','w+');
fwrite($file, json_decode($json));
fclose($file);
} else {
syslog(LOG_DEBUG,"Failure");
return "Failure, json decode is null";
}
closelog();
return "Success";
?>
In the log I get:
Mar 14 14:50:54 scriptLog.txt[21902] : Received Data
Mar 14 14:50:54 scriptLog.txt[21902] : Failure
In the debug div text I get:
{"1457981454959":{"id":1457981454959,"code":"1","title":"Test","date":"22/03/2016","description":"a Task"}}RESPONSE: , error: SyntaxError: JSON Parse error: Unexpected EOF
1) How can I examine the posted data? I.e. "Received Data: "+WHAT in syslog to see its structure.
2) JSON parse error? Most examples I see use this stringify function. then they use json_decode to get the values. Why the parse error?
1) How can I examine the posted data? I.e. "Received Data: "+WHAT in syslog to see its structure.
As I understand you are debugging the code, so syslog can be not the best idea.
I would simply use the browser network console to see the content of requests and a simple php file like this to see the content of $_POST:
<?php
echo json_encode($_POST);
In more complex cases - use the actual debugger.
2) JSON parse error? Most examples I see use this stringify function. then they use json_decode to get the values. Why the parse error?
You are trying to use the json key in your $_POST, but you didn't instruct jQuery to add it, so you are receiving not what you expected.
There are few issues with your $.ajax call, here is the commented version:
$.ajax({
type: 'POST',
url: './json.php',
dataType: 'json', // Note: dataType is only important for the response
// jQuery now expects that your server code
// will return json
// here you need to add the 'json' key
data: {'json': JSON.stringify(data)},
// the success method has different order of parameters
//success: function(xhr, status, errorMessage) {
success: function(data, status, xhr) {
alert("response was "+data);
},
error: function(xhr, status, errorMessage) {
$("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
}
});
Now on the server you will have $_POST['json'] with serialized string and you can json_decode it.
Alternatively you can send the JSON data without serialization:
var data = {'test': 'abc'};
$.ajax({
type: 'POST',
url: './json.php',
// No 'JSON.stringify()', just send your data
data: data,
...
});
And on the server you will have $_POST['test'] with abc value (so you have your json already converted into array).

Ajax getting cancelled in browser

When I click and run my ajax script, I see this error in Chrome:
Status: cancelled
The json data returns to the page in the url bar. My sql table is updating but the error message I indicate above is displaying and the modal doesn't remain open. I suspect there could be a few problems here but I wonder if anybody notice something.
This ajax script is inside a PHP variable that is why you may see some escaped characters. Here the $row is a PHP array. Please don't get confused.
$("document").ready(function() {
$(".form-inline'.$row["userid"].'").submit(function(event) {
event.preventDefault;
var formData = new FormData($(".form-inline'.$row["userid"].'")[0]);
console.log();
$.ajax({
type: "POST",
dataType: "json",
url: "sponsorship.php",
data: formData,
success: function(response) {
if (response.success) {
$("#myModal'.$row["userid"].'").modal(\'show\');
$(".form-inline'.$row["userid"].'").hide();
$("#paypalform'.$row["userid"].'").show();
$("#alertmessage'.$row["userid"].'").show();
$("#closebutton'.$row["userid"].'").hide();
}
else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
contentType: false,
processData: false,
error: function() {
alert("this error is getting displayed");
}
});
});
});
event.preventDefault is a function. You're referencing it, but not calling it.
The default action of the submit event will therefore happen, causing you to leave the page and terminate the JS.
Don't forget to put () when you are trying to call a function.
The problem is with String conctatination on your JS :
$("#myModal'.$row["userid"].'").modal(\'show\');
$(".form-inline'.$row["userid"].'").hide();
$("#paypalform'.$row["userid"].'").show();
$("#alertmessage'.$row["userid"].'").show();
$("#closebutton'.$row["userid"].'").hide();
You have to either fix the concatination :
$("#myModal'.$row['userid'].'")
Or I'm assuming you are missing the php tags on $row

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 call and simple PHP json string echo server

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 :(

Categories