jQuery json ajax function - javascript

I am having a kind of a weird problem, or maybe I do not understand how js and jQuery is working.
I have a small js that is sending an id and a value using AJAX. After a lot of experimentation I finally found a working solution which is:
$.post('dashboard/xhrDeleteListing', "id=" + id, function() {
alert(1);
});
However, I would like to use json format for the data part of the call. So what I did (to make sure that my JSON is correct) was the following:
var myJSON = {
id: id
};
$.post('dashboard/xhrDeleteListing', JSON.stringify(myJSON), function() {
alert(1);
}, 'json');
But this didn't work. First, php server didn't get anything (nothing in $_POST), second, the callback function didn't run (alert(1) was never executed). To my surprise, the following call did create a $_POST['id'] value:
$.post('dashboard/xhrDeleteListing', {'id': id}, function(z) {
alert(1);
}, 'json');
but again the callback function didn't run. It only run after removal of 'json' datatype argument).
The version of jQuery is v1.11.0.
Can anyone help me to figure out what am I doing wrong?
Regards,

The important point here is when you do this like:
$.post('dashboard/xhrDeleteListing', {'id': id}, function(z) {
alert(1);
}, 'json');
the 'json' paramter is the dataType of data expected from the server, not from you to send.
It means in your backend after doing your server side task you have to return a valid json string but it seems you want to do a server action without any return value, that's why you have to remove 'json' from your arguments.

var myJSON = {
"id": "id"
};
$.post('dashboard/xhrDeleteListing', JSON.stringify(myJSON), function() {
alert(1);
}, 'json');

Try this :
$.ajax({
url: 'dashboard/xhrDeleteListing',
type : 'POST',
dataType : 'json',
data: {
'id':id,
},
success : function(callback_record) {
alert(callback_record);
}
});

Related

how to change the code from $.ajax() to $.getJSON

this code works using ajax and I want to change it using json, what is the right way to use it?
AJAX
$('#movie-list').on('click', '.see-detail', function() {
$.ajax({
url: 'http://omdbapi.com',
dataType: 'json',
data: {
'apikey' : 'myapikey',
'i' : $(this).data('id')
},
success: function (movie) {
$('.modal-body').html(`...`);
}
})
});
JSON
$('#movie-list').on('click', '.see-detail', function() {
$.getJSON('http://www.omdbapi.com/?apikey=myapikey&i=='+ $(this).data('id') +'', function(data) {
$('.modal-body').html(`...`);
});
});
Look at the documentation:
jQuery.getJSON( url [, data ] [, success ] )
So:
jQuery.getJSON(
'http://omdbapi.com', // url
{ // data
'apikey' : 'myapikey',
'i' : $(this).data('id')
},
function (movie) { // success
$('.modal-body').html(`...`);
}
);
While you could munge the query string on to the URL by mashing strings together: Don't. We use libraries to do it because they are less error prone and know all the rules for properly escaping data.

Ajax and PHP, post request not working

So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});

MVC 5 generate form data with AJAX

I need a way to generate a new unique id for a user when a person focuses out of a textbox. I am using MVC 5 for this application. Here is my controller, everything in the controller has been unit tested and it does return the string value that I need.
Controller. I was able to visit that URL, and I did download a JSON file with the correct data.
public ActionResult GetNewId()
{
string newId = utils.newEmployeeId();
return Json(new {eId = newId}, JsonRequestBehavior.AllowGet);
}
Javascript, JQuery call to that controller. I do not know how to properly reference the ActionResult. I keep getting undefined errors on eId.
$(function () {
$('#employeeId').focusout(function () {
if($("#employeeId").val() === "NP")
$.ajax({
type: 'GET',
url: '#Html.ActionLink("GetNewId", "Employees")',
data: { 'eId': eId },
dataType: 'json',
success: function (response) {
$("#employeeId").val(eId);
},
error: function (response) {
alert(response);
}
});
});
});
The problem is with yout ajax request:
1.you need to change the url in the reuqest but it like this
{{yourcontroller}/GetNewId}
2.remove the "data: { 'eId': eId }" you dont need it, youre not posting anything to the server.
change your $("#employeeId").val(eId); to
$("#employeeId").val(response.eId);
this will 100% work

Mapping data with ajax returns zero

I've been working with ajax to get input values from a form when it's submitted, but when I look into the console it comes back as 0. I'm not too familiar with ajax overall, so I'm not sure if I'm not using this correctly or if I have an error somewhere else.
Here's what I have:
JS:
jQuery(this).find(".form-item").on("submit", function(e) {
var $this = jQuery(this);
if (this.checkValidity()) {
e.preventDefault();
$.ajax({
url: Config.ajaxurl,
type: 'POST',
dataType: 'json',
accepts: 'application/json',
context: this,
data: {
action: 'process_form',
form_info: {
"input_18_16": $(this).parents('.form-item').find('#input_18_16').val() || '',
"input_18_17": $(this).parents('.form-item').find('#input_18_17').val() || '',
"input_18_3": $(this).parents('.form-item').find('#input_18_3').val() || '',
"input_18_2": $(this).parents('.form-item').find('#input_18_2').val() || ''
},
},
success: function(data, status, xhr) {
console.log('Response:\n', data)
console.log('successful trigger');
console.log($(this).find('#input_18_16').val());
},
error: function(xhr, code, error) {
console.log(error)
}
})
}
});
The crazy thing is that I can get the data correctly from this:
console.log($(this).find('#input_18_16').val());
In the console. Which but for some reason the console.log('Response:\n', data) comes back as Response:0 so I'm not sure why it's successful but not able to return anything?
In the success function you should use $this instead of $(this). That's why you set it in the first place, isn't it?
You can also use it in the data: option, since it's more efficient to reuse the variable instead of calling jQuery() repeatedly.
the data in 'console.log('Response:\n', data)' is actually being returned from the success function after ajax returns successful. Is is not the same as the data you are posting to Config.ajaxurl.
Check the missing ";" on the line console.log('Response:\n', data).
And I think the "\n" not affects the console.log mensage.
EGG: After this, checkout it https://api.jquery.com/serialize/ may be make your life more easy

JQuery Ajax not sending data to PHP

myscript.js below is outputing:
[{"orcamento":"10","atual":"20","desvio":"","data":"2015-01-01","nome_conta":"BBB","nome_categoria":"abc","nome_entidade":"def"}]
myscript.js:
if (addList.length) {
$.ajax($.extend({}, ajaxObj, {
data: { "addList": JSON.stringify(addList) },
success: function (rows) {
$grid.pqGrid("commit", { type: 'add', rows: rows });
},
complete: function () {
$grid.pqGrid("hideLoading");
$grid.pqGrid("rollback", { type: 'add' });
$('#consola').text(JSON.stringify(addList));
}
}));
}
The JSON data above has to be sent to my script.php below:
if( isset($_POST["addList"]))
{
$addList = json_decode($_POST["addList"], true);
var_dump ($addList);
echo "test";
exit();
}
Although the data is correct and myscript.php is being called it isn't returning anything. I get:
NULLtest
I tried using GET, instead of POST but the result is the same, what is wrong with the code above?
EDIT:
Here's the ajaxObj used in the ajax request:
var ajaxObj = {
dataType: "json",
url:"../myscript.php",
type: "POST",
async: true,
beforeSend: function (jqXHR, settings) {
$grid.pqGrid("showLoading");
}
};
From the PHP Docs on json_decode:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
So it is most likely that there is some error in your JSON data that is preventing json_decode from parsing it correctly, I've ran that snippet through jsonlint and it does say that it's valid JSON, but it's worth checking a larger sample of the data you send to the server for inconsistencies.
Other than that, is there any reason that you are calling JSON.stringify on the data object prior to sending to the server? I would try just sending the object itself as the data parameter of your AJAX call like so:
$.ajax($.extend({}, ajaxObj, {
data: { "addList": addList },
success: function (rows) {
$grid.pqGrid("commit", { type: 'add', rows: rows });
},
complete: function () {
$grid.pqGrid("hideLoading");
$grid.pqGrid("rollback", { type: 'add' });
$('#consola').text(JSON.stringify(addList));
}
}));
And see if that helps:
EDIT
I should have noticed in my original answer, you will not need to call json_decode on your posted data, jQuery encodes the data as post parameters correctly for you; It should be accessible within your PHP script as an associative array, try replacing your current var_dump statement in your PHP var_dump($_POST['addList'][0]['orcamento']); and you should be good to go.
First of all, be sure you are posting to a php file, use firebug or similar tools to track your script..
I don't see the part you defined the target PHP file on your javascript file..
A regular javascript code can look like this :
jQuery.ajax({
type : "post",
dataType : "json",
url : 'target.php',
data : {foo:bar },
success: function(response) {
// do something with response...
}
});
If you see that you are posting to the right php file the right parameters on firebug, try to use $_REQUEST if $_POST not working..
Firebug will show you the response of PHP file.. so do a print_r($_REQUEST['addList']) to see what is going on...

Categories