AJAX (JQuery) Returning Error Unexpectedly - php

I have this Jquery AJAX request to process the creation of Word documents (using PHPWord). The reports are processed and, as far as I am aware, I should not get an error. Whilst the reports are processed, I cannot get the 'data' response from the page, which returns the processed file's name which is needed to provide download links.
The AJAX request looks like this (it is based upon list items with the class 'selected'):
$('.selectionList.unprocessed li.selected').each(function(index) {
params = 'reportNo=' + ($(this).index() + 1);
$.ajax({
url: 'word/export.php',
data: params,
dataType: 'script',
type: 'post',
success: function(data) {
increaseProgressBar();
},
error: function(jqXHR, textStatus, errorThrown) {
increaseProgressBar();
alert('failure ' + textStatus + ' and ' + errorThrown);
}
});
});
increaseProgressBar() just increases the width of the coloured part of a progress bar.
The errors I get in the alert boxes are either:
failure parsererror and SyntaxError: Unexpected identifier
or (both are received seemingly randomly)
failure parsererror and SyntaxError: Unexpected identifier
I attempted to post to this page using a form and that worked fine and the page echoed the correct response.

Very simple solution - I just need to change the dataType from script to text and the rest of it works fine.

Related

JQuery Ajax not working when two browser tabs are open on the same domain

I have a very strange problem when working with JQuery and PHP AJAX.
I have a form that submits via AJAX and it works fine. The problem is, when I load another page from the same site in another browser tab, my ajax request no longer works in my other tab.
Here is the code I'm currently using:
Javascript:
$("#step-edit-form").submit(function(e){
e.preventDefault();
var data = $(this).serialize();
//Update order in the database
$.ajax({
type: 'POST',
url: ajax.ajaxurl,
data: data,
dataType: 'json',
cache: false,
success: function(data){
if(data.success == 0) {
$('.message').html(data.message).fadeIn()
console.log(data.message);
}
else if(data.success == 1) {
$('.save').hide();
$('.message').html('Saved Successfully').fadeIn().delay(3000).fadeOut();
formmodified = 0;
}
},
error: function(xhr, ajaxOptions, thrownError, request, error) {
console.log('xrs.status = ' + xhr.status + '\n' +
'thrown error = ' + thrownError + '\n' +
'xhr.statusText = ' + xhr.statusText + '\n' +
'request = ' + request + '\n' +
'error = ' + error);
}
});
});
I get this in console:
xrs.status = 200
thrown error = SyntaxError: Unexpected end of input
xhr.statusText = OK
request = undefined
error = undefined
The PHP returns nothing at all.
Like I said, this only happens when I load another browser tab on the same domain, otherwise everything works fine. I've tested in both Chrome and FireFox, same issue in both browsers.
I have these two pages open in the two tabs:
Tab 1: http://localhost/sbs/admin/edit-step/18 (This is my tab with ajax)
Tab 2: http://localhost/sbs/ (I load this tab after at which point the ajax in my first tab no longer works properly)
You are facing the error 'Undefined end of input' which means there are some cases when you are getting wrong response then expected.
Possible causes for this error
Your code is broken from server side. Just like using exit statement
You are missing comma(,), braces({,})
Your code returns null data
That is not a issue of opening in new tab, It's an issue of unexpected data
i think contentType missing in your ajax call.
Please add below contenttype in your ajax request.
"contentType": "application/json; charset=utf-8",
this is issue in you ajax call OR server side run time error or parameter related issue to call service.
ajax request always call on multiple tabs for same domain.

Error - Passing an array from PhP to jQuery using JSON

I apologise, since I know this has been asked before, more than once.
I've been struggling with this little bugger for quite a few hours now, and I cannot seem to find my mistake.
The problem is simple - I have a PhP array which I want to pass over, from the server side to the client side, using jQuery AJAX with the data in JSON format.
The code for my Client-side Ajax call is
$.ajax({
url: 'php/test/pass_array.php',
method: 'POST',
data: {test1: 'abc', test2: 'cde'}, //Random input data
dataType: 'json',
success: function(response_data)
{
console.log(response_data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(arguments);
console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
}
});
And the code for my server-side pass_array.php script is
header('Content-type: application/json; charset=utf-8');
echo json_encode(array("Name"=>"Johnny")); //Build JSON object from the array
As you can see, this is pretty basic, but it's not working. On the client side, the AJAX response is never received.
When I check the browser console log, I get
Error: SyntaxError: Unexpected token parsererror [object Object]
What the devil am I doing wrong?
All my files are in UTF-8 encoding. This also works if I remove the dataType: 'json' and the heading() on the PhP side. In that case, I get the following string:
{"Name":"Johnny"}
UPDATE
Commenting out the header() code in the PhP side makes the console show the following error:
Uncaught SyntaxError: Unexpected token o
How can there by syntax errors? I create a PhP array and encode it using json_encode.
UPDATE #2
Fixed it.
On my PhP file I had (only one more!) line
include '../core/db_io.php';
I commented that line out and it worked fine.
This file contains methods to query my databases. Since I did not call any methods or objects from this file, I left it uncommented - thinking it made no difference.
It looks like including that db_io.php file added a Byte Order Mark character (\ufeff) to the JSON string.
The complete string being sent to the Client side was
\ufeff{"Name":"Johnny"}
It seems this db_io.php file was encoded with BOM. Changing its encoding (using notepad++) fixed that.
Amazing how a simple include instruction can mess up an AJAX call.
Try checking out if your ajax function is being triggered and if any request is even being sent to your php code. For example maybe there is some syntax in your ajax script or you have not provided the url of your php file.
Make sure your PHP script starts with <?php
Update 1:
I made two files on my localhost - index.html
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<script>
$.ajax({
url: 'pass_array.php',
method: 'POST',
data: {test1: 'abc', test2: 'cde'}, //Random input data
dataType: 'json',
success: function(response_data)
{
console.log(response_data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(arguments);
console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
}
});
</script>
</body>
</html>
pass_array.php
<?php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array("Name" => "Johnny"));
The result of the AJAX call in the console is:
Object {Name: "Johnny"}
Make sure the url is correctly accessing the right php file.
You can check any "XHR" requests (AJAX) in Chrome's inspector under the "Network" tab.
Fixed it.
On my PhP file I had (only one more!) line
include '../core/db_io.php';
I commented that line out and it worked fine.
This file contains methods to query my databases. Since I did not call any methods or objects from this file, I left it uncommented - thinking it made no difference.
I still don't understand tho - I'm not using that file in any way - other than include it. Why should it interfere?
Thanks for the ideas. Peace!
Error: SyntaxError: Unexpected token
U have problems with 'token' variable. Mb u use CMS or Framework?
Try
console.log(arguments);
And also, u can try send
header('Content-type: application/json');

AJAX Call Not Sending Success Response

//MAKE AJAX CALL TO REPOPULATE TABLE
var newData = 'page_number=1&type=2';
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'http://www.myurl.net/form_validate.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
//REFORMAT UPON SUCCESSFUL AJAX CALL
alert(response);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
All I've put in my PHP file is:
<?php echo "test"; ?>
When I go straight to that file, it echoes 'test.' When I try to run the AJAX function on the click of a button it gives me the error:
[object Object] error
in an alert window. I've put the absolute URL to the file because I was thinking that the relative linking I was using was wrong but it now seems like it's some other issue. Am I overlooking a simple syntax error? Sorry if this is super basic but I can't seem to figure this out after working on it for a really long time. Thanks for your help.
The problem is your absolute url . Some browsers have problems dealing with absolute urls, consider it as a cross-domain request and block it even if it's not a cross-domain request. You should try with relative url instead
The problem might be in the url, try with relative path instead of absolute.
You named the file was in the same folder as the .js file, so try
url: '/directory_path_to_the_same_folder_as_the_JS_file/form_validate.php',
Try using done with jQuery.post instead.
For example:
jQuery.post('form_validate.php', data).done(
function(data, textStatus, jqXHR) {
alert(jqXHR.responseText);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
}).complete(function() {
// Common code when request completes
});
If your error is [object Object] error NOT FOUND then the reason is
the specified url in AJAX is not correct.
If your error is [object Object] error INTERNAL SERVER ERROR , its
because of the error in your server file ie the php file ,error like variables not defined correctly etc..
Some times error may occur due to cross domain, if you have not
specified headers when in case your php file is not in the same
domain
Hope this helps
Thank you
function abc(){
var ret=true;
$.ajax({
type: 'POST',
url: 'send_password.php',
data: 'mail_to=mymail&new_password=pwd',
async:false,
success: function(response){
},
error: function(r){
ret=false;
}
});
return ret;
}
alert(abc());
Have a look at this testfiddle

jquery ajax php call not working correctly

I copied this ajax call from another one that works and I can't figure out why it's not successfull. Here is the code:
$.ajax({
type: "POST",
url: "addTune.php",
data: {
database: setlist,
name: tune,
orderno: orderno,
midi: midi
},
error: function (e) {
alert("The PHP Call failed! hmmm");
alert(e.status);
},
success: function (response) {
alert(response);
}
});
I get the error function every time. Are there any blaring typos or other stupid mistakes?
Edit: trying to chase down the error with:
$.ajax({
type: "POST",
url: 'addTune.php',
data: {database : setlist, name : tune, orderno : orderno, midi : midi},
error: function(e){
alert("The PHP Call failed! hmmm");
alert(e.status);
$.ajaxSetup({
"error": function(jqXHR, status, thrownError) {
alert('error');
var responseText = jQuery.parseJSON(jqXHR.responseText);
console.log(responseText);
}
});
},
success: function(response){
alert(response);
}
});
});
Update: I was just able to add a row with the command line. any thoughts as to what I can do to try and narrow this down further?
i am no pro at this but maybe using single quote instead of double quotes? because i'm working on a project were i also have to do ajax calls and i use single quotes
i'm just suggesting something, not really good at this
If you get into the error callback then you have an error with the page you are calling and not with the js code. Check if the php page is reached. If it is check the php code if it returns a valid result.
From jquery DOCS.
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A
function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn. Note: This handler
is not called for cross-domain script and JSONP requests. This is an
Ajax Event.

Is that possible to call to external PHP script from Ajax?

I'm trying to call to external PHP script using Ajax like this:
$(function() {
$.ajax({'url': 'http://stokes.chop.edu/web/zscore/result.php',
'type': 'POST',
'success': function(response, textStatus, XMLHttpRequest) {
alert('[' + response + ']');
},
'error': function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error');
}
});
});
The result is: [] (i.e. success function is called!),
but I see the following error in HTTPFOX plugin for FireFox:
Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED)
What's wrong with my code ?
You cannot load contents from pages that does not have the same domain name as the one from which the ajax request is called from. This is a well known security feature call the Same Origin Policy.

Categories