Multiple AJAX calls with errors - javascript

I'm trying to make a generic function that allows me to get data from different sources at the same time.
I based my solution on this post, and ended up with this:
var servicesURL = 'http://www.somedomain.com/services/xml_proxy.php?url=';
function getExternalData(service, callback) {
$.ajax({
type: 'GET',
url: servicesURL+service,
dataType: 'jsonp',
jsonpCallback: 'myfunction',
success: function(data) { callback(data); },
error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus+': '+errorThrown); }
});
}
getExternalData('data1.xml', function(data) {
console.log(data)
});
getExternalData('data2.xml', function(data) {
console.log(data)
});
Here's the code of the proxy I'm using:
<?php
header('Content-type: application/json');
$url = $_GET['url'];
echo 'myfunction('.json_encode(simplexml_load_file($url)).')';
?>
It works fine when I make a single call to the function, but when I make more that one call (as I did above), I get the following errors:
parsererror: Error: myfunction was not called
Uncaught TypeError: Property 'myfunction' of object [object Object] is not a function
Any help would be highly appreciated

Try putting the second call inside the callback of the first. That should fix the issues you are having.
http://forum.jquery.com/topic/multiple-jsonp-requests-causing-errors

Related

Calling a PHP returning a JSON returns an error though I can see the response

This is the javascript I'm using to make an AJAX call to a PHP:
$(document).ready(function(e) {
$(function(){
$.ajax({
type:'GET',
dataType: 'jsonp',
data: {
country: "uk"
},
url: 'http://api.mysite.uk/advertorial/index.php',
success: function (response){
var result = $.parseJSON(response);
console.log(result);
},
error : function () {
console.log('Error');
}
});
});
});
which returns a JSON structured like this:
{"id":"1","name":"test","country":"uk","header":"Header","pre_cta_text":"Pre CTA","cta_text":"CTA text","cta":"CTA","img":null,"active":"1"}
Even if the call gives an error, I can see that it's returning the JSON above. I particular the error I get in browser console is:
Uncaught SyntaxError: Unexpected token :
index.php?callback=jQuery32103297264247416809_1516181997373&country=uk&_=1516181997374:1
You instruct jQuery to ask for JSONP and decode it automatically:
dataType: 'jsonp',
Then you take jQuery's decoded data and handle it as JSON, which is not and has never been:
success: function (response){
var result = $.parseJSON(response);
console.log(result);
}

How to make a generic ajax function for php file

I hope you can understand my question. I am trying to make a generic ajax function that will send some data to a php file and get the server's response. There is a very similar question here jquery - creating a generic ajax function , however I am having some troubles sending the data in a json format. Let me provide you the JS code:
function CallMethod(url, parameters, successCallback) {
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(parameters),
contentType: 'application/json;',
dataType: 'json',
success: successCallback,
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
var pars = {
id:"1",
message:"hello world"
};
function onSuccess(data) {
console.log(data);
}
CallMethod('ajaxGeneric.php', pars, onSuccess);
And now here is my php file 'ajaxGeneric.php':
<?php
$id = $_POST["id"];
$msg = $_POST["message"];
echo $id;
echo $msg;
?>
When I run the page I have this error in the Chrome's console:
SyntaxError: Unexpected token < in JSON at position 0(…)
The php file seems also to have some problems trying to get the post values. What am I doing wrong? sending the data? getting the data back?
Any help will be greatly appreciated.
Try removing JSON.stringify and pass the parameters directly,So that your function will look like this
function CallMethod(url, parameters, successCallback) {
$.ajax({
type: 'POST',
url: url,
data: parameters,
contentType: 'application/json;',
dataType: 'json',
success: successCallback,
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}

PHP _POST with Ajax not working

I have the following JavaScript code:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js'></script>
<script>
function sterge(id_user){
console.log(id_user);
var mesaj_post ='id_user=' + id_user;
$.ajax({
type: 'post',
url: 'deleteStudent.php',
data: mesaj_post,
dataType: 'text',
cache: false,
success:function(data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}
});
}
</script>
The problem is that in the PHP file called by function, POST is empty and I don't understand why. The parameter of the function is not empty/null, and script result is SUCCESS
PHP Code:
<?php
include 'connect.php';
if(isset($_POST['id_user']))
echo $_POST['id_user'];
else
echo "empty post";
?>
Can you help me fix it? Any help would be appreciated.
Thank You!
As #charlietfl first said in his comment, the replace was the problem. But not only that one. The form was also doing a replace.
Thank You!
I pointed out in my comment
Remove the window.location.replace - it calls your php with a GET and no id_user
Had you posted your form too, we could have seen you did not cancel the submission. I hope you did that with something like
$("#formID").on("submit",function(e) {
e.preventDefault();
$.post("deleteStudent.php",{ "id_user":$("#id_user").val() }, function(data) {
console.log(data);
});
});
of course this error occurs, you pass a string not josn object to correct this error you should do the following in javascript code :mesaj_post ={'id_user': id_user}; :)
Try with this code this may do helpful for you
function sterge(id_user){
console.log(id_user);
var mesaj_post = {
"id_user":id_user
};
$.ajax({
type: 'post',
url: 'deleteStudent.php',
data: mesaj_post,
dataType: 'text',
cache: false,
success:function(data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}
});
}

Variable undefined after Ajax request

I have a globally defined JavaScript function which performs an ajax request to fetch some data from a model. The issue I am having is that when I load the page and inspect element, it gives the error:
Uncaught ReferenceError: response is not defined
Here is the function:
function getRating(work_id)
{
$.ajax({
url: '/read/getRatings',
type: 'GET',
async: true,
data: { field1: work_id},
success: function (data) {
//your success code
response = data;
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + thrownError);
}
});
return response;
}
The function gets called in my HTML like this:
<div class="extra">
<script>
document.write(getRating(112));
</script>
</div>
Error in browser console]:
The Ajax request works fine as when I inspect it in Chrome's developer tools, the correct response comes back. However the variable response does not get initialized in the $.ajax() method.
When I try to add $response = ""; at the start of the function so that it gets explicitly defined, it always returns the empty string and the variable does not get changed inside the ajax request as it should.
Anyone know what's going wrong here?
This is a common misunderstanding of asynchronous programming. You don't have a result to return when the initial call ends-- you need a callback to do the writing for you (the success part).
function getRating(work_id, selectorToWriteTo)
{
$.ajax({
url: '/read/getRatings',
type: 'GET',
async: true,
data: { field1: work_id},
success: function (data) {
//your success code
$(selectorToWriteTo).html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + thrownError);
}
});
}
HTML:
<div class="extra" id="myDiv">
<script>
getRating(112, '#myDiv')
</script>
</div>

Getting data through jQuery ajax request

I'm using the following code to get the dataa from the server:
$.getJSON('http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod?callback=?', dd, function (data) {
alert(data);
});
From the server, I'm sending the byte array as response.
In firebug, in Net > Response tab, I get:
jQuery19101878696953793153_1365677709012([67,37,94,38,42,44,69,67,71,32,97,116,116,97,99,104,101,100,32,102,111,114,32,112,97,116]);
Also in Net > JSON tab, I get data with several keys.
But how to get the data at alert(data);; so that I process on that data.
I don't know, how this thing works.
Edit:
I tried this different approach:
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/javascript",
data: dd,
crossDomain: true,
url: "http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod",
success: function (data) {
alert(JSON.parse(data));
},
complete: function (request, textStatus) { //for additional info
alert(request.responseText);
alert(textStatus);
},
error: function(request, textStatus, errorThrown) {
alert(textStatus);
}
});
But I got: parseerror as alert.
From looking at the docs (I haven't tried this) you need to explicitly tell jQuery that you're making a JSONP call that will invoke the function that's returned. Something like this:-
$.ajax({
type : "GET",
dataType : "jsonp",
url : "http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod",
success: function(data){
alert(data);
}
});
Function you are looking for is JSON.parse. Please try this code :
$.post("YouURL", { 'ParameterName': paramvalue }, function (Data) {
var data = JSON.parse(data);
});
Your response is a function call. If u define function name with name jQuery19101878696953793153_1365677709012 you can process the 'data' else from your server just send the json as a response to $.getJSON's callback to work
The problem was the data was very huge. I was sending array of around 10,00,000+ bytes.
So instead I divided it into list of bytes (each having 1000 bytes) & then sent as response.
I don't know if this is the best solution, but it solved my problem.
BTW, thanks to all for helping me.

Categories