SyntaxError: syntax error in ajaxFileUpload jquery plugin - php

i want to pass other parameters with file to save in database.when i put code to get those variables and save in database it give me alert "SyntaxError: syntax error"...
here is my code
$.ajaxFileUpload
({
url:'popup/doc_mydeal.php',
secureuri:false,
fileElementId:'deals_documents',
dataType: 'json',
data:{rand_key: $('#rand_key').val(), document_name: $('#document_name').val()},
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}
}
},
error: function (data, status, e)
{
alert(e);
}
})
Now on doc_mydeal.php
$tempFile = $_FILES['deals_documents']['tmp_name'];
$targetFile=$path.$_REQUEST['rand_key'].basename($_FILES['deals_documents']['name']);
move_uploaded_file($tempFile,$targetFile);
and here is mysql query to save in database

When you specify a dataType of json in the options for the jQuery AJAX call you're telling the code that the server will be returning valid JSON. Based on this information jQuery will implicitly parse the response text as JSON, passing the resulting object as the argument of the callback function.
In the case that the response text isn't valid JSON the parse will fail and the error callback will be executed instead. As has been pointed out in the comments, what you're returning from your PHP script is invalid JSON.

Related

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).

Jquery callback error: Uncaught TypeError: Cannot read property 'length' of undefined

I have a form to call ajax for back-end processing, all input will stored in table and will return 'success' to to notify user the submission is success. But I facing an issue during callback, input data can saved into table but the callback is halted with error below, I have no idea what is goes wrong, the same script was applied to another form (with different form field) are working pretty well, please help for solution.
console log (Chrome):
Uncaught TypeError: Cannot read property 'length' of undefined
m.extend.each
$.ajax.success
j
k.fireWith
x
b
Firefox
TypeError: a is undefined
...rCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e...
Script:
$(document).ready(function() {
$("#status").hide();
$('#btn_submit').click(function(){
var params = $('#project_form').serialize();
var btn = $(this);
btn.button('loading')
$.ajax({
url: baseurl + '/process_form.php',
type: 'POST',
data: params,
dataType: 'json',
success: function(response){
if(response.success == 'success'){
$('#status').html('<b>Thank you</b>').show();
$('html,body').animate({
scrollTop: $('#top').offset().top
},500);
}else{
$('[id$="_error"]').html('');
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
}
},
error: function(){
console.log(arguments);
}
}).always(function(){
btn.button('reset')
});
});
});
first: When you want to use ajax with submit don't use submit click .. use form on submit better
$('#project_form').on('submit',function(){
var params = $(this).serialize();
second: if in success you echo('success') in process_form.php you should use
if(response == 'success')
and use response instead of response.error
Hope it will help
Your problem is the way you use the success callback method. The manual says:
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
So it does not get a .success or .error passed along unless you yourself make sure it's returned from the url you are doing the ajax to. (If you are doing this, then don't read the rest of my answer, and use Element Inspector to see if the .success and .error are actually inside the returned data.)
So now your if (response.success == "success") is false, because it's actually undefined. And the response.error is also undefined, so $.each(response.error, ...) gives you your problem, since you cannot .each an undefined.
It is normal to just assume you are successful, since you are inside the success handler.

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

AJAX/JQuery success:/error: function manipulation

Having some trouble with AJAX/JQuery. Here is the context of my problem followed by a code sample:
What I am attempting to do is call a PHP script called getInfo.php and check whether or not some data is contained within a database. I can write queries easily enough but in terms of the code sample below how can I "tell" the success function to fail if it cannot find data in the database and run the error function instead?
$(document).ready(function(){
getInfo();
function getInfo(){
$.ajax({
type: "GET",
url: "getInfo.php",
data: "do=getInfo",
cache: false,
async: false,
success: function(result) {
$("#myInfo").remove();
alert("Data found");
},
error: function(result) {
alert("Data not found");
}
});
}
});
Any advice would be greatly appreciated. =)
The error handler is used to handle errors in your AJAX call.
You could echo 1 in your PHP script if the data was found and 0 if it was not found. Then you could use an if statement to determine what to do. For example:
success: function(result)
{
if(result == 1)
{
$("#myInfo").remove();
alert("Data found");
}
else
{
alert("Data not found");
}
},
"success" gets called when the returned code is a "200" (successfull request).
"error" gets called whenever another code is returned (e.g. 404, 500).
So I think you can do 2 things:
Let PHP return a 404 so the error function gets called
Let your getinfo.php return a boolean value (usually my approach)
{"success":true, ...}
The 'error' function you're using is for identifying and handling an AJAX error, not a script error. If the script you're calling is found, and it executes without terminating unexpectedly (ie, it has errors!), then its considered a success.
The best thing to do is have your getInfo.php script return something you can use within the success function; such as the number of rows in your result set or something - then you can check in success() whether you have data and code accordingly.
I think your getInfo.php page should just print SUCCESS or FAIL and in your success method do
success: function(result) {
if (result == 'SUCCESS')
{
$("#myInfo").remove();
alert("Data found");
}
else
{
alert("Data not found");
}
}

Get jQuery Error if PHP Breaks

I have a PHP script that breaks if a variable is not populated and it isn't added to the database, but jQuery handles this as a success and I get this error:
TypeError: Result of expression 'data' [null] is not an object.
Here's the jQuery script:
$.ajax({
type: "POST",
url: "/clase/do-add",
data: $("#adauga").serialize(),
dataType: "json",
error: function (xhr, textStatus, errorThrown) {
alert('Try again.');
},
success: function(data) {
var dlHTML = '<dl id="' + data.id + '"> [too long] </dl>';
$('form#adauga').after(dlHTML);
$('#main dl:first').hide().fadeIn();
adaugaClasaSubmit.removeAttr('disabled');
adaugaClasa.removeAttr('readonly');
adaugaClasa.val("").focus();
}
});
The problem is that jQuery's concept of "error" is an HTTP error, not an error that you have noted yourself. If the HTTP response code is <400, jQuery will use your success callback. Your options are (a) to use PHP to give an error in your HTTP response
header("HTTP/1.0 500 Internal Server Error");
or (b) to do your error handling in the success handler:
success: function(data) {
if (!data) {
// do your error code here
} else {
// do your success code here
}
}
I prefer the first option, with HTTP response codes, to allow your code to make the best logical sense to a future editor (which may be you!).
success: function(data) {
if(data!=null){
...
}
}
try this

Categories