My AJAX function keeps getting error as result - javascript

I'm new using AJAX or jQuery and I'm trying to insert some data in a table whitout loading another page, I can't tho.
Here is my AJAX func:
Edit:
function SumbitAction(act_id) {
$.ajax({
dataType: 'json',
type: "POST",
url: 'Accion.php',
data: {Action:act_id},
success: function (obj, textstatus) {
if(obj.status==='FAIL') {
console.log(obj.message);
}
else {
console.log("ok");
}
}
});
}
And in my PHP I'm giving no arguments at the moment to test a full null insert query: Edit:
$consultaAcciones= "INSERT INTO acciones VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
$ejecAcciones = mysqli_query($conn, $consultaAcciones);
if($ejecAcciones===false){
$response = [
'status' => 'FAIL',
'message' => 'Accion no registrada correctamente'
];
}
else {
$response = [
'status' => 'OK',
'message'=> 'Accion registrada'
];
}
header("Content-type: application/json");
echo json_encode($response);
I am getting "Error" in the console logs and I don't know what's wrong. Edit: No longer
Edit:
Now it doesn't display any error, it's okay, but also doesn't show my console logs for when everything's okay, also am getting a warning message:"Cross-Origin Read Blocking (CORB) blocked cross-origin response"
and a log: XHR finished loading: POST "http://url...".
may it be is not correct to specify the callers of my function this way?
function addListener(id,num)
{
var target= document.getElementById(id);
if(target){
target.addEventListener("click",SumbitAction(num),false);
}
else{
//console.log("Nel",id);
}
}

There are 2 problems in the code.
First, if(('error')) { will always evaluate as true. 'error' is just a string, and that is truthy.
You probably meant to compare that string against something, maybe (also removing doubled parentheses):
if (textstatus === 'error') {
Next, textstatus is the status of the request, not of your code. It will be error when, for eg, there is a 404, or a 500 response from the server. If your INSERT fails, the http request will still be successful, and textstatus will not be error.
You might want to check textstatus in an error() callback, if you want to add one. But within the success() callback, you probably want to be checking what your code returned. In this case, that is obj.
But looking at the PHP, it does not return anything predictable that the JS can use. It returns nothing if the query works. If it fails, it returns a string that begins with Error but then shows a MySQL error, which we won't know ahead of time, so you can't test for it in JS.
It would be better to simply return some true/false, OK/fail type msg, for eg:
// ... rest of your code
$result = mysqli_query($conn, $consultaAcciones);
if ($result === false) {
echo "FAIL";
} else {
echo "OK";
}
And in your JS:
if (obj === 'FAIL') {
// ... etc
If you actually want to pass a message back from the PHP, you should have it echo out a JSON object, eg:
$result = mysqli_query($conn, $consultaAcciones);
if ($result === false) {
$response = [
'status' => 'FAIL',
// You shouldn't reveal internal details about errors
// so don't return mysqli_error(). Maybe log it, and
// display something generic to your users.
'message' => 'There was a problem'
];
} else {
$response = [
'status' => 'OK',
'message'=> ''
];
}
header("Content-type: application/json");
echo json_encode($response);
In your JS:
$.ajax({
// ...
// specify we will get a JSON response
dataType: 'json'
// ...
success: function (obj, textstatus) {
if (obj.status === 'FAIL') {
alert(obj.message);
} else {
// all ok ...
}
});

Related

ajax response data is undefined

i have problem with ajax post submit
here is my script
function postad(actionurl) {
if (requestRunning) return false ;
if (! $("#editadform").valid()) {
validator.focusInvalid();
return false ;
}
$('#ajxsave').show() ;
requestRunning = true ;
var postData = $('#editadform').serializeArray();
$.ajax(
{
url : actionurl,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$('#diverrors').html(data.errors) ;
$('#divalerts').html(data.alerts) ;
if (data.status=='success') { alert(data.status);
$('#siteid').val(data.siteid) ;
if ($('#adimager').val())
$('#divlmsg').html(data.alertimage) ;
$('#editadform').submit() ;
} else {
$('#ajxsave').hide() ;
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('#ajxsave').hide() ;
},
complete: function() {
requestRunning = false;
}
});
$('.btn').blur() // remove focus
return false ;
}
This works on if (textStatus=='success') {
but when the action fails, alert(data.status) shows Undefined.
Using FireBug, I can see that the data is correctly returned. Why is data.status "Undefined" then?
If you don't specify the dataType field of an $.ajax() call in jQuery, it formats the response as plain text. A workaround to your code would be to either include dataType: "JSON" into your $.ajax() parameters, or alternatively, in your success function, parse the plain text response as a JSON object, by using the folllowing:
data = JSON.parse(data); // You can now access the different fields of your JSON object
UPDATE:
yes i have not status field in action url, how to add data status field in php code?
When creating your PHP script that is intended to return the JSON data, you first need to build an array and then encode it as JSON.
So, suppose you have a PHP script that either succeeds and produces some data that you put into a $data variable, or fails, then the following style could be adopted:
<?php
// ^^ Do your PHP processing here
if($success) { // Your PHP script was successful?
$response = array("status" => "success!", "response" => $data);
echo json_encode($response);
}
else {
$reponse = array("status" => "fail", "message" => "something went wrong...");
echo json_encode($response);
}
?>

Access JSON Ajax Response data

I have added a property to a JSON data but I cannot access the data on JS it does not show. I am not new to Ajax and JSON but it is a apparent that I still have gaps in my knowledge when it comes to Ajax. Please help me understand how i can append data to my Ajax response.
I have this in a PHP controller class:
$x = '5';
if($request->ajax()){
return response()->json([
'total_questions' => $x,
'responseText' => $e->getMessage(),
], 500);
}
I want to access the total_questions property with JS/JQuery..
My JS AJAX callback is here:
console.log('errors -> ', data.total_questions); - returns undefined
$.ajax({
type:"POST",
url: APP_URL+"selfEvaluation/save",
data:$(this).serialize(),
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(data){
var errors = data.responseJSON;
console.log('data -> ', data);
console.log('errors -> ', data.total_questions);
if(data.status == 422){
// alert('422');
}
}
});
This is my console result
error: function(data){
is an incorrect method signature. See the definition at http://api.jquery.com/jquery.ajax/.
It should be
error: function(jqXHR, errorThrown, textStatus){.
You'll need to access the jqXHR.responseJSON property. So:
console.log('errors -> ', jqXHR.responseJSON.total_questions);
But I would question why you're returning a "500" status code for this request, when it appears to be a valid response. "500" means "Internal Server Error", which implies the server crashed, when it appears that it did not. If you return a "200" ("OK") status, your ajax code will go into the "success" callback and you can directly reference the "data" object in the callback to read your data.
try this if you will get a json response from your browser.
if($request->ajax()){
$result = array(
'total_questions' => $x,
'responseText' => $e->getMessage(),
], 500);
}
echo json_encode($result);

Why is this object parse returning undefined?

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

Retrieving posted data from ajax using php

I have a problem retrieving the posted data from an ajax call, not sure what is wrong. The console output from the script below shows everything as expectred before the ajax call, but the data is not available in the connector
function updateOptions(data){
console.log(data);
console.log(data.id);
console.log(data.action);
var data = {id: data.id, action : data.action};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.connector.php?action=updateOptions',
data: JSON.stringify(data),
cache: false,
dataType : "json",
success: function(data, status) {
if(data.status == 'success'){
console.log('success');
console.log(data);
}else if(data.status == 'error'){
console.log('selects not updated');
}
},
error: function(data){
console.log('an error has occurred');
},
});
}
So the first 4 console.log entries show the data correctly, the first console.log in the success condition shows correctly. The second, shows:
Object {status: "success", msg: "Category added successfully", id: null, action: null, post: Array[0]}
the connector [more like a director]
case 'updateOptions':
error_log('Running updateOptions function ' . print_r($_POST, TRUE), 0);
$output = $sbb->updateOptions($_POST);
break;
Logs this:
Running updateOptions function Array\n(\n)\n,
if I try to echo $_POST['action'] or $_POST['data'] or something to the log I get an undefined index.
I am forcing the ajax call to return success in the class that the php case function is calling:
public function updateOptions($data){
$output = array(
'status' => 'success',
'msg' => 'Category added successfully',
'id' => $data['id'],
'action' => $data['action'],
'post' => $data,
);
return $output;
}
So the ajax call itself does work, it's the data that's not being passed.
Somehow I am not getting [or correctly retrieving] the data from the ajax post.
What is the problem here?
You're posting JSON, $_POST is populated with key=value pairs, don't mix up JSON with application/x-www-form-urlencoded or multipart/form-data (which is what php uses to populate $_POST.
To send application/x-www-form-urlencoded data with jQuery.ajax pass an object with the data as the data parameter
data: data, // removed JSON.stringify

AJAX form not submitting that gives error

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

Categories

Resources