I have my AJAX code here
$("#add-student").click(function(e) {
e.preventDefault();
formData = $("#student-form").serialize();
if (cleanFormInput()) {
sendTheInfo(formData);
} else {
shakeForm();
}
});
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
Always without fail outputs this error:
Connection error:
SyntaxError: Unexpected end of input : parsererror
But still gives the complete message: Everything complete
Update, PHP code here:
require '../../core/init.php';
require '../../classes/Config.php';
header('Content-Type: application/json');
if (!empty($_POST)) {
$id = $_POST["sid"];
$first = $_POST["first"];
$last = $_POST["last"];
$fav = "0";
$sql = "INSERT INTO `students` (`id`, `first`, `last`, `active`) VALUES ('{$id}', '{$first}', '{$last}', '{$fav}')";
$link = mysql_connect(Config::get('mysql/host'),Config::get('mysql/username'),Config::get('mysql/password')) or die("could not connect");;
mysql_select_db(Config::get('mysql/db'), $link);
$result = mysql_query($sql, $link);
if ($result) {
header('Content-Type: application/json');
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
}
}
I'm a bit confused, am I doing my ajax set up wrong? Or is it something else in by backend code wrong? I'm using MySQL and jQuery 2.0.3
Updated code here: here
I have had a look at your code. I saw that from the PHP side you are sending a JSON object. but you didn't specified the return dataType for the response. Try to add the dataType in the ajax call. Maybe that will solve the problem
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
dataType : 'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
It should be noted that the Ajax COMPLETE method will fire even if the back end does not return a result.
complete: function() {
console.log("Everything complete");
}
will thus show the log'ed entry every time an ajax call is 'finished executing', even if the submit failed.
I would also suggest NOT having 2 headers or the same declaration (you have one up top, and one in the if(result) call.
In a comment thread, you pointed out that you're working on the server but not locally, And thus that implies you have some pathing issues. Check your
../
relative path style urls and make sure that you have the same basepoints.
removed my old answer. I don't think it is an ajax/javascript error. it's definitely a PHP error. It's this lines:
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
You $student_data is not an array, it's just a string. You need to pass an array into the json_encode function
Related
i have a little problem with ajax and mysql.
I want to save same data to a database via ajax.
Javascript:
$.ajax({
type : "POST",
url : url_save,
async : false,
data : { item : nr, var : text },
success: function(result_save){
if (result_save.includes('Error')) {
alert("!!! Error !!!");
}
},
error: function(xhr, textStatus, errorThrown) {
alert("!!! Error !!!");
}
});
My PHP-File looks like:
PHP:
<?php
require "config.inc.php";
$db = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME) or die ('Error');
$db->set_charset("utf8");
$sql="INSERT INTO tbl (item, var) VALUES ('$_POST[item]','$_POST[var]')";
if (!mysqli_query($db,$sql))
{
return 'Error';
die();
}
mysql_close($db);
return 'i.O.';
?>
It saves to the database, but the error-function of ajax is executed every time. What is wrong?
A few observations:
jcubic is correct- you don't want to use a JS keyword as a parameter name.
catcon is also correct. Using a prepared statement is FAR preferable to reading the variable directly into your SQL text.
Even if mysqli_query() returns 0, you still want to do a mysql_close($db), don't you?
You would also like to know the specific error, wouldn't you?
SUGGESTION:
PHP:
<?php
require "config.inc.php";
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO tbl (item, var) VALUES (?, ?)");
$stmt->bind_param("is", $_POST[item_id], $_POST[item_value]);
if (!$stmt->execute()) {
$result = "Execute failed: (" . $stmt->errno . "): " . $stmt->error;
}
$stmt->close();
$conn->close();
return ($result) ? 'Success' : $result;
...
JS:
$.ajax({
type : "POST",
url : url_save,
async : false,
data : { item_id: nr, item_value: text },
success: function(result_save){
if (result_save === 'Success') {
console.log('Insert was successful', nr, value);
} else {
alert('mySql Error: ', JSON.stringify(result_save));
}
},
error: function(xhr, textStatus, errorThrown) {
alert('XHR Exception: ' + textStatus + ', ' + JSON.stringify(errorThrown));
}
});
As the title says I want to run the if and else inside the success condition in Ajax, For example after running the Ajax and sees that there is a record it will go to success then inside the success it must look for the "if statement" and display the alert inside the "if statement" if the statement is true but instead it always display the "else statement" with the alert('no') inside of it, even if there is a record, Thank you
<script>
function renderAttendees(id)
{
///$("#attendeesContent").empty();
var dataString = { "id": id };
$.ajax({
type: 'POST',
url: server+'webservice/crm/viewAttendeesDetails',
data: dataString,
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
cache: true,
success: function(data)
{
if($.trim(data) === 'error')
{
alert('yes');
}
else
{
alert('no');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error connecting to server. " + XMLHttpRequest + ", " + textStatus +", "+ errorThrown);
}
</script>
//My Controller Code
public function viewAttendeesDetails()
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
$data = array();
$id = $_POST['id'];
$AttendeesDetails = $this->model->GetAttendeesDetail($id);
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
}
echo json_encode($data);
exit;
}
?>
//My Model Code
db->prepare("SELECT * FROM crm_contact_list WHERE id = :AttendId");
$stmt->bindParam(":AttendId", $id);
$stmt->execute();
return $stmt;
}
catch (Exception $e)
{
return $e->getMessage();
return $stmt;
}
return;
}
?>
//Here is the result of console.log(data);
Object
email:"kyle#localhost.com"
full_name:"Test kim"
id:"1"
interest:"Test"
number:"123456"
position:"Prog"
venueID:"1"
I would return from your controller something like
{status: 'success', data: myArrayWithFoundData}
so when you receive the ajax response you could do a json_decode, and check the status.
So in you controller you would have
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
$rsp_data = {status: 'success', data: $data};
}else{
$rsp_data = {status: 'error', data: null};
}
echo json_encode($resp_data);
Something like that, so in the ajax response you would do a
var a = JSON.parse(data);
and check the a.status for error
Sorry about this nth version of object grabbing, but I just don't see it.
I am returning a JSON object from a db to my Javascript, and I see the returned object (below) just fine in the console. But the moment I attempt to put a child in the console I get "undefined". I should be able to see result.bills, or result["bills"] and just to be sure I've tried result[0].bills, etc. all of which are undefined. This seems so basic but I can't see why I can't make this work.
My PHP (after db stuff):
if ($result) {
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[bills] = $r;
}
echo json_encode($rows);
} else {
echo "Unknown Error";
}
//all done
My AJAX:
$.ajax({
type: 'get',
url: 'GetBills.php',
success: function(result) {
var thebills = result.bills;
console.log(thebills);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
and I get back:
{
"bills": {
"ID": "3",
"State": "MD",
"Title": "Maryland Android Project Act (S.1196 H.2057)",
"HouseNum": "H 2057",
"SenateNum": "",
"Session": "189th"
}
}
You're getting undefined because jQuery doesn't know that it's actually receiving JSON back. It is detected and automatically parsed if you send JSON headers with your php file, OR if you set the dataType to 'json'.
So, currently you're accessing a string:
var result = '{"bills":{"ID":"3","State":"MD","Title":"Maryland Android Project Act (S.1196 H.2057)","HouseNum":"H 2057","SenateNum":"","Session":"189th"}}'
BUT you're attempting to access STRING functions (specifically bills which is undefined).
If you choose to not change the dataType or add headers, you could also do result = JSON.parse(result) which would also give you the same thing.
Doing one of the three above solutions will give you the object you're looking for, and access its children:
//Javascript
result = JSON.parse(result);
//In Console
Object {bills: Object}
bills:
ObjectHouseNum: "H 2057"
ID: "3"
SenateNum: ""
Session: "189th"
State: "MD"
Title: "Maryland Android Project Act (S.1196 H.2057)"
__proto__: Object
__proto__: Object
add dataType to your ajax request object:
...
type: 'get',
url: 'GetBills.php',
dataType: 'json',
...
You can either force the content type to be JSON in your AJAX call, or even better, set the correct content type in your PHP and let jQuery detect it automatically. Imagine accessing your data from another tool different from jQuery, e.g. a mobile app or some REST-tool. If you set your Content Type properly, most tools/languages will detect it automatically and you don't have to parse it manually over and over again.
// Set the content type correctly
header('Content-Type: application/json');
if ($result) {
$rows = array();
while ($r = mysqli_fetch_assoc($result))
{
$rows[] = $r; // Notice how to append the row to the array
}
http_response_code(200); // PHP >= 5.4
echo json_encode([
'success' => true,
'bills' => $rows
]);
}
else {
http_response_code(500); // Your status code here
echo json_encode([
'success' => false,
'message' => 'Something went wrong',
]);
}
And your JavaScript:
$.ajax({
type: 'get',
url: 'GetBills.php',
success: function(result) {
var thebills = result.bills;
console.log(thebills);
},
error: function(response) {
console.log('Error', response.message);
}
});
I am trying to delete images with Ajax and all the php seems to work except when I try to send variables to another php document.
Php that shows and grabs neccessary values.
// show images
$image_display = "";
foreach(glob($pathimages.'*') as $filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$name_only = basename($filename, ".".$ext);
$image_display .= "<img src=\"images/" .$targetID."/" .$name_only.".".$ext. "\" width=\"30\" />
<a onclick=\"DeleteImage('".$name_only."','".$ext."','".$targetID"'); return false;\" href=\"javascript:;\">X</a>
<br />";
}
.JS document, I get the sent and the success messages when pressing the X
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
delete_imgs.php document
include('session_check.php');
$name_only = $_POST['name_only'];
$ext = $_POST['ext'];
$targetID = $_POST['targetID'];
$pathimages = "images/$targetID/";
unlink($pathimages . $name_only .".". $ext);
echo "Deleted";
Any thoughts are more than welcome since I have banged my brain out of my head by now ...!
Cheers!
Try with async:false
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
async : false,
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
Maybe that can help
my json script is:
// add button .click
$('a.add').click(function(){
$('#loader').show();
var url = "/?"+$("form[name='jsms_add']").serialize();
ajx = $.ajax({
url: url,
type: 'post',
data:{ajax:1},
dataType: 'json',
success: function(r) {
$('#loader').hide();
if(r.r != 0){
alert("ok");
jsmsalert($('#alert_add'),'success',r.m);
apendtable(r.r)
$("tr").removeClass("odd");
$("tr.viewrow:odd").addClass("odd");
$("tr.editrow:odd").addClass("odd");
$('td[colspan="7"]').remove();
}
else{
jsmsalert($('#alert_add'),'error',r.m,0);
}
},
error: function(request, status, err) {
$('#loader').hide();
jsmsalert($('#alert_add'),'error','error...');
alert( "ERROR: " + err + " - " );
}
});
and in my php file i have
$data = array(
'r' => '1',
'm' => '1',
);
json_encode($data);
now i want to know that how can i send a value to json that r.r != 0 be true and my success code execute?
In Firefox the error is "SyntaxError: JSON.parse: unexpected character"
this code used by another site by i don't know what happend in php file
my problem is that how can i send some data (for example r=1) to my json, because i want to check that if r=1 (means success) do something and show text from m (message) in my page
please help me to correct php file
thank
In your php file make sure you are echoing the encoded data,
like so:
$data = array(
'r' => '1',
'm' => '1',
);
echo json_encode($data);
If you don't echo the data it will not make it back to your JavaScript.
If your JavaScript is what's throwing the errors try commenting out the dataType: 'json', and console logging the return. It might be php is throwing errors that jquery is refusing to parse.
$.ajax({'url': url,type: 'post',data:{ajax:1}, success: function(returnData){
console.log(returnData);
}});