Cross Domain jQuery Ajax call - Syntax missing error - php

I couldn't access the webservice call from cross domain. Please advice. I have pasted my source here.
PHP: webservice response
$data['response'] = 2;
header('Content-type: application/json');
echo json_encode($data);
jQuery Ajax Call:
$.ajax({
type: 'GET',
url: cross-domain-url,
data:{ param1:'123', param2:'123' },
dataType:'jsonp',
crossDomain: 'true',
async: true,
success:function (data) {
alert('success');
},
error:function(){
alert('error');
}
});
Cross Domain URL response:
{"ResultCode":2}
Always I am getting Error only. I don't know why. I can see the following message in Firefox inspect area.
SyntaxError: missing ; before statement
{"ResultCode":2}
Please help me.
Solution:
Modify the line like,
echo 'someCallBackString('.json_encode($data).');';
instead of echo json_encode($data);
Created the function someCallBackString and proceeded my implementations.

You are telling jQuery to make a JSON-P request (dataType:'jsonp'), but your server is returning JSON.
Consequently the browser is trying to execute a JSON text as if it was a JavaScript program (and it can't because it isn't).
Either:
Remove the dataType property from the object so that jQuery will use the HTTP Content-Type to determine that it is JSON and add access control headers to permit your site to access the data on the other domain or
Return JSON-P instead of JSON

Ok the problem is in the JSONP data, when you send a request the JSON response would send a response as
callbackFunctionName(jsonData)
You do not have anything as such so is the issue you need to format the code as below
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'your cross domain file',
dataType:'jsonp',
crossDomain: 'true',
jsonpCallback: 'MyCallback',
async: true,
success:function (data) {
console.log(data);
},
error:function(data){
console.log('error');
}
});
function MyCallback(data) {
}
});
Now in the response the data needs to be formatted as
$data['response'] = 2;
header('Content-type: application/json');
$json_data = json_encode($data);
echo "MyCallback" . '(' . $json_data . ');';
You can now check your console and see the data is coming through
You can check more on this here http://remysharp.com/2007/10/08/what-is-jsonp/

change your ajax to this code:
Solution
$.ajax({
type: 'GET',
url: cross-domain-url,
data:{ param1:'123', param2:'123' },
dataType:'JSON',
success:function (data) {
alert('success');
},
error:function(){
alert('error');
}
});
Hope it will work....

Related

Ajax call returning empty data

I send an ajax call on the following URL and just echoing the response but unable to see in success function.
Where am i wrong ?
html file
$.ajax({
url: '{$PLUG_DIR}/cb_memcached/admin/ajax.php',
data: {
mode: 'videos'
},
type: 'post',
success: function(xhr) {
alert(xhr);
}
});
php file
<?php
echo "asasas";
?>
Your code seems OK. Please double check your URL. Hit your URL from browser to see response. This issue is only because of your PATH.
Issue seems to be some where in {$PLUG_DIR}. Still Call error and complete function to debug it.
$.ajax({
url: '{$PLUG_DIR}/cb_memcached/admin/ajax.php',
data: {
mode: 'videos'
},
type: 'post',
success: function(xhr) {
alert(xhr);
},
error: function(error) {
alert(error);
}
});
If you need to send data structure :
JS
$.ajax({
url: '{$PLUG_DIR}/cb_memcached/admin/ajax.php',
data: {
mode: 'videos'
},
type: 'post',
success: function(xhr) {
var param1 = xhr.param1;
alert(param1);
}
});
PHP
<?php
$response = array();
$response["param1"] = "param1";
echo json_encode($response);
?>
Please check below scenarios:
Make sure you include jquery plugin.
URL path should be correct.(In your case this may be wrong)
To check the error from ajax call please open inspect element from chrome and check the response in network tab.

Ajax post not appending data to URL

I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.

AJAX request returning error

I have an AJAX request that is throwing an error.
It's part of a larger system that I've inherited, so I can't post the files in their entirety, but I've tried to isolate the relevant code:
$.ajax(
{
url: ajax_url, // Valid URL
data: jsonData, // Valid JSON
dataType: 'json',
contentType: 'application/json',
type: POST,
async:true,
success: function(data)
{
console.log(data);
parsedData = JSON.parse(data);
console.log(parsedData);
// Here I am trying to log successful output
},
error: function(jsonData)
{
console.log("error");
console.log(jsonData);
}
});
In the PHP, values are added to an array and returned:
$data['status']=200;
$data['new_id']=$insert_id;
return json_encode($data);
All I am logging at the moment is 'error'. Apologies again for incomplete code, I have tried to supply the code where I think the error is caused.

Get json with jQuery mobile from localhost

I create a JSON object with fisrtTest.php
The JSON is correct when I open this page with WampServer ..
But I cannot do a Ajax request :/
Why ? Cross domain policy ?
$.getJSON('http://localhost/tests/fisrtTest.php',
success
);
function success(data) {
}
This is for a mobile app with phonegap
$(document).ready(function(){
$("#ibutton").click(function() {
alert("go");
$.ajax({
url: "http://localhost:8080/tests/fisrtTest.php?callback=?",
dataType: "json",
crossDomain: true,
success: function(data) {
}
});
});
});
Well, this works but firebug gets an error :
SyntaxError: invalid label
{"jack":1,"gt":2,"c":3,"d":4,"e":5}
What is your error? Can you view JSON response in the firebug console?
Below is working code
$(document).ready(function(){
$("#ibutton").click(function() {
alert("go");
$.ajax({
url: "http://localhost:8080/tests/fisrtTest.php",
dataType: "jsonp",
crossDomain: true,
jsonpCallback: "CallBackFunction"
});
});
});
function CallBackFunction(json){
//
};

Issue with my JSON callback

I am using the following code to get json from my web service while the service is outputing the correct values I cannot access it I get an error stating that its undefined when I try to alert part of the object. How can I fix this issue?
My code is below
jQuery
var durl = "a valid url";
$.ajax({
type: "GET",
url: durl,
data: "Pass="+avalidid,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "callback",
contentType: "application/json",
crossDomain: "true",
}).done(function(){
}).fail(function(){
$.mobile.changePage("errorpage");
})
});
//callback function
function callback(rtndata)
{
alert(rtndata.name);
}
Web service
The last few lines to return json
echo $_GET['onJSONPLoad'];
echo "(" . json_encode($posts) . ")";
Lastly it should be mentioned that I mapped my array so that it can return all of my results
$posts[] = array_map('utf8_encode',$post);

Categories