submitting a form using $.ajax - javascript

I'm calling this function when the dom is ready on $().submit
but it seems not working there is no response from server
$(function(){
$("#logingform").submit(function(){
var values =$(this).serialize();
call_server("../php/login.php",values);
});
});
function call_server(URL,DATA)
{
$.ajax(
{
type:'POST',
url : URL,
data : DATA,
dataType:'json',
success:function(response){
$("#d1").append(response);
}
}
);
}
nothing seems to get back from the server.
server code
<?php
$email = $_POST['loginemail'];
$password =$_POST['loginpassword'];
echo json_encode(array('returned_val' => 'yoho'));

There is an extra semi colon following your ajax option:
data : $(this).serialize();,
vs correct
data : $(this).serialize(),

You do not need to parse the json that is returned, since you already have dataType:'json' defined in the ajax options.
$("#d1").append($.parseJSON(response));
That is not necessary.
If you want to show the response object as a string, then you need to stringify it instead:
$("#d1").append(JSON.stringify(response));
Also, you have a syntax error on this line:
data : $(this).serialize();,
Remove the ;.
Your data for a POST should be in json format, so rather than $(this).serialize(), use $(this).serializeArray() for your data. This will pass those values for POST body rather than in the querystring.

Related

AJAX - Why page redirect is failing here?

I have a problem here. I am posting data using $ajax to update a MySQL table. The update logic is done fine.
PHP Snipet
$count=$stmnt->rowCount();
if ($count==1){
$output=array('op'=>'tt');
echo json_encode($output);
}else{
$output=array('op'=>'ff');
echo json_encode($output);
}
JS Code
success: function(data) {
console.log(data);//On update, this is printing{"op":"tt"}
if (data.op ==='tt') {
console.log(data);//this is not executing.
window.location.href= 'post.php'
}else{
alert("Error!");
}
}
I have realized that my if statement is not being executed. What has gone wrong here?
By default, jquery ajax without a dataType will try to set the response based on the MIME type.
If you have a string, you can manually parse it, ie:
success: function(data) {
data = $.parseJSON(data);
or you can specify the dataType for jquery to use on the $.ajax request.
You should parse the json first before you can get the plain text out of it.
var result = jquery.parseJSON(data);
if (result.op == 'tt') {
...
}

Sending data from javascript to php using via Ajax using jQuery. How to view the data back?

I know this question has been asked a lot as I have been googling since morning but I just can't think what's going on in my code.
I have a index.php (which is my website) that uses forms to receive information from user, then invokes a javascript file separately which in turn invokes another backend php file (this backend php file queries a database using mysql and does some stuff).
The problem is I am not sure what information is getting passed to the backend php from my js. I have just learnt jQuery and Ajax so I really don't know what is that small mistake I am making.
From my understanding, the backend php does its stuff and passes the value to javascript to be displayed on the web page. But my data is not getting sent / displayed. I am getting a error 500 internal server error.
Here are the pieces of code that are currently is question:
Javascript:
var data1 = {week:week, group:grp_name};
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
success : function(response){
alert ("success !");
},
error : function(response){
console.log(response);
alert("fail!");
}
})
});
PHP backend (remindUsers.php):
<?php
if (isset($_POST['week'])) {
$week = $_POST['week'];
}
if (isset($_POST['group'])) {
$group_name = $_POST['group'];
}
echo $week;
?>
I am ommiting out the sql code pieces because they work fine.
Edit: Now my status code is 200, response text is also ok . My response text shows a weird "enter' sign next to the actual response text expected. Is this normal ? And it is still going into the error block , not the success block of code.
I can not fully answer your question because I need more debug information about whats going on but theres 2-3 things about your code bugging me a little that might fix your bug.
First, use isset in your backend like this:
if (isset($_GET['your_input_name'])) {
$someData = $_GET['your_input_name'];
}
The isset part is very important here. Set it up and try it again. If you stop having a 500 error. Its probably because your data was never send to your backend or because your not checking the good input name.
Second, About input name. I can see in your code that you send:
var data1 = {week:week, group:grp_name};
So in your backend you should use the name of the value like this to retrieve your data:
$week = $_POST("week");
Third, I am not a json pro but maybe your json is not valid. Even if he is ok I suggest you build a "cleaner" one like this:
var data = [
{ 'name' : 'week', 'value' : week}
];
And finally, if you are using forms to send data to php then you can use something like that :
var myForm = $("#myForm").serializeArray();
$.ajax({
url: 'yourUrl',
type: "GET",
data: myForm,
dataType: 'json',
success: function(res){
//your success code
},
error: function(){
//your error code
}
});
I hope this helps.
You can't have these tags <body>,... in your PHP response over json.
It must be only:
<?php
$week = $_POST("data");
$json = json_decode($week);
echo json_encode($json);
?>
Remove the comment on
//data : {week :week}
And set a variable week with a valid value:
data : {week :week}
and so:
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
data : {week :week} ,
success : function(response){
console.log(response);
},
In order to see what is the shape of response.
You are doing a couple things wrong. First, you don't want to stringify your data before sending it to the server. You want to send JSON, so your commented line is the correct one. There is also a problem with the PHP. The data going to the server will look like:
{week: "Something"}
So in your PHP, you want to access the data like:
$_POST["week"];
USE THIS
PHP
$week = $_POST['data'];
$json = json_encode($week);
echo $json;
JS
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php"
//data : {week :week} ,
data: {data:{week:'week', group:'grp_name'}} ,
success : function(response){
alert ("success !");
},
error : function(response){
alert("fail!");
}
})
I would say wrap the php in a function and echo the json. Also its good to check if there was POSTed data, and if not return an error message. This is not tested, but will hopefully point you in the right direction.
<?php
function getJSON() {
if (isset($_POST["data"] && !empty($_POST['data']) ) {
$week = $_POST["data"];
$json = json_decode($week);
echo $json;
} else {
echo "There was a problem returning your data";
}
}
getJSON();
?>
Actually as I write this, I realized you could try these headers in your AJAX POST:
accepts: 'application/json',
contentType: 'application/json',
dataType: 'json'
Hope that helps.
It worked. I figured out the answer thanks to another SO post.
TIL : Even if server response is ok, the error condition will be triggered because the data returned to javascript from php is not json,since i had explicitly mentioned dataType: "json" in the ajax request.
Link here:
Ajax request returns 200 OK, but an error event is fired instead of success
Thanks folks for helping me and steering me in the right direction. Cheers!

Parsing JSON returned via an AJAX POST formating issue

I have a php returning some json in response to a POST request made via an ajax function.
In my php function I format the data like this:
//json return
$return["answers"] = json_encode($result);
echo json_encode($return);
This returns the following string:
answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"
And this is where I am trying to catch it to use the data:
$.ajax({
type: "POST",
url: "http://ldsmatch.com/pieces/functions/question.functions.php",
dataType : 'JSON',
data: dataString,
success: function(data) {
alert(data.answers[0]["aa"]);
}
});
I've been trying to just alert the data so I can visualize it before setting up the vars I need, but am having some trouble formatting it correctly so it is usable.
If I alert data.answers[0] then it just shows me the first character in the string, which is a bracket [ and if i subsequently change the number it will go through each character in the returned string.
I have tried other variations, such as:
data.answers[0]["aa"] (this returns 'undefined' in the alert)
data.answers["aa"] (this returns 'undefined' in the alert)
data.answers[0] (this returns the first character of the string)
I feel like I'm close, but missing something. Any guidance appreciated.
edit:
thanks for all the suggestions. I removed the second json_encode and was able to parse with data.answers[0].aa
success: function(data) {
var json = $.parseJSON(data);
alert(json.answers[0]["aa"]);
}
Use parseJson like this
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
What if you remove double-encoding on PHP side? You've got an object with JSON string instead of object with first property being object itself, or you may explicitly decode "answers" property on client side as it was suggested above.

Return info from jQuery AJAX call and execute additional jQuery on success

I have the following jQuery AJAX to duplicate a background image. I am stumped as to how to effectively return information back to the original page. Here is the AJAX I send on click of "'#dupBtn"...
//DUPLICATE BACKGROUND
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
"user":<?= $_POST['user'] ?>,
"bgID":bgID,
"refID2":<?= $_POST['refID2'] ?>,
"refTable":"<?= $_POST['refTable'] ?>",
"bgTitle":($('#bgTitle').val()),
"path":path,
"bgColor":bgColor,
"bgPoz":bgPoz,
"bgRepeat":bgRepeat,
"attach":attach
}
});
});
Here is the basic MySQL query on the PHP page bgUpdate.php.
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
What I want to do is have the following code fired on the original page upon successful execution of the MySQL entry, dynamically catching the '$bgIDnew' from the MySQL PHP page.
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
You can accomplish this with the success attribute of the .ajax() function:
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
...
},
success:
function(response)
{
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
});
});
That's only part of it though... The other half is that your PHP needs to return something that jQuery can understand as a "successful" call. My preference is to use HTTP status codes. In your case, your PHP script should return a 200 code if it was successful; otherwise, it should return something in the 400 range. (By the way, if you want jQuery to do something separate with errors, you can use the error property of .ajax().)
However, if you need to return data from the server to the client-side script, then your PHP can print out that information like this:
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
// Best practice to keep it in some sort of understandable format
// Here, we'll put it in an associative array:
$response = array('id' => $bgIDnew);
print_r(json_encode($response));
This PHP script sends back to the ajax() method a JSON representation of the $response variable. You've already configured that ajax() method to read the response dataType as JSON, so it already knows how to read the response parameter... Which means your success function can look something like this:
success:
function(response)
{
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=' + response.id);
}
jQuery.ajax() has a success property that acts as a callback that you can use. Another is complete which is fired if the request is successful or not.
jQuery.ajax({
/* your stuff here */
success: function(response) {
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
});
You can write up the logic in the success callback function of your ajax Request..
This is fired when an ajax request is successfully returned..
success: function(response) {
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
Add this to your ajax Request...

Array of objects not getting parsed as javascript array of native objects?

I am receiving following data from server
"[{\"role_id\":\"1\",\"name\":\"administrator\",\"created_by_user_id\":\"2\",\"time_created_on\":null,\"is_user_based\":\"0\"},{\"role_id\":\"2\",\"name\":\"manager\",\"created_by_user_id\":null,\"time_created_on\":null,\"is_user_based\":\"0\"}]"
which is simply an array of two objects . Even after setting 'dataType' to json I am not receiving native javascript array inside my success callback function but if I use
$.ajaxSetup({
url:'/public/admin/role/list',
dataType:'json'
});
$.ajax({
success:function(data) {
alert(data[0].name); // alert box pop up as 'undefined '
var data = $.parseJSON(data);
alert(data[0].name) ; //works
}
});
Don't escape the ". They're required for JSON parsing.
[{"role_id":"1","name":"administrator","created_by_user_id":"2","time_created_on":null,"is_user_based":"0"},{"role_id":"2","name":"manager","created_by_user_id":null,"time_created_on":null,"is_user_based":"0"}]
You have a trailing comma when setting dataType in your ajaxSetup method:
dataType:'json',
^
Also I hope those \ in the JSON you have shown here are not part of the actual response from the server. The response should look like this:
[{"role_id":"1","name":"administrator","created_by_user_id":"2","time_created_on":null,"is_user_based":"0"},{"role_id":"2","name":"manager","created_by_user_id":null,"time_created_on":null,"is_user_based":"0"}]

Categories

Resources