How to include variable inside AJAX data - javascript

I am trying to send an Ajax request but I wanted to include variables that I have already defined in the data that is sent to the server.
I'm not quite sure how I can escape the data part and put a variable where I have stated...
$.ajax({
url: './json/delete.php',
type: 'POST',
async: false,
data: { SD_FieldDisplayName : <VARIABLE HERE>,
SD_FieldSeq : <VARIABLE HERE>,
SD_TableSeq : <VARIABLE HERE>,
SD_ViewName : <VARIABLE HERE> }
dataType: 'json',
success: function(result)
{

You forgot a comma after your data object.
$.ajax({
url: './json/delete.php',
type: 'POST',
async: false,
data: { SD_FieldDisplayName : <VARIABLE HERE>,
SD_FieldSeq : <VARIABLE HERE>,
SD_TableSeq : <VARIABLE HERE>,
SD_ViewName : <VARIABLE HERE> },
// You need a comma here ^
dataType: 'json',
success: function(result)
{
}
});

You can just reference the variable in the value of the key:
var someVar = 3;
data: { SD_FieldDisplayName : someVar }

You're almost there. You need to include in the variables you want to send through your AJAX request. Here's a stripped example. I've used $.post but $.ajax is essentially the same. It takes the data from a form with the class .formclicked (which other code labels with the class .formclicked. It sends through a 'relations' data with $_POST['relations'] and a method flag $_POST['method']. The first is defined by the form, the second is defined y the submit button in the form, that's not sent by serialise. The serialise function converts the form data in #an_id into a form suitable for AJAX.
// Comments
jQuery(document).on('submit','#an_id' ,function(){
$data = jQuery(this).serialize();
var selector = jQuery(this);
$method = jQuery(this).find(".formclicked").attr('value'); // Get clicked form
jQuery.post('your_ajax_form.php', {action:'hook_update',relations:$data, method:$method},
function(answer){
if(jQuery.isNumeric(answer)){
if(answer) {
// Response Code Based on Condition
}
else {
// Handle failures
jQuery(selector).find(".formclicked").removeClass('.formclicked');
}
}
else {
}
return true;
}
);
return false; // Prevent the page from refreshing
});

Please use this one :
var val1;
var val2;
var val3;
var val4;
$.ajax({
url: './json/delete.php',
type: 'POST',
async: false,
data: { SD_FieldDisplayName : val1 , SD_FieldSeq : val2 , SD_TableSeq : val3 , SD_ViewName : val4 },
dataType: 'json',
success: function(result)
{
}
});
please define variable inside of the function where you want call this ajxa call or global

Related

Getting Certain values from an AJAX return JSON object

I am trying to retrieve certain values in a JSON object retrieved from AJAX.
Using console.log(), I was able to view these:
0: Object
title: "First post"
body: "This is a post"
id: 1
userId: 27
.
.
.
100: //same format of data as object 0
Now I want to try storing the whole JSON object above so that I can use the userId and match it with another list of data to find the user who made the post. Problem is, I can't store it to a global variable. Here is my jscript snippet:
var postJson; //global variable
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
console.log(response);
}
});
I also tried doing postJson = $.ajax but nothing happened and postJson continues to be undefined.
$.ajax is async function, you need to use callback or do all the code in success function
var postJson; //global variable
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
//do something with postJson or call function doSomething(response)
}
});
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
doSomething(response);
//do something with postJson or call function doSomething(response)
}
});
You can do directly via calling function from response no need to declare variable. Hope it will also helps you

I am passing an ajax to php with datatype as JSONP,but showing undefined index in php file

On submit button click,
I am passing a variable to sendmail.php.It's showing that contactname is undefined in php.
why is it happening ?
Here is my Code :
var name = document.getElementById('stream_cotactname').value;
alert(name);
$.ajax({
url: "sendmail.php",
async: false,
type:"POST",
data : "cotactname="+name+"file=" + formdata,
dataType: "jsonp",
contentType: false,
processData:false,
jsonp: "jsoncallback",
success: function(html){
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
My Php File:
<?php
$name =$_POST['cotactname'];die("A".$name);
?>
ALL gone well,Thanks.
Now let my introduce my exact code:
<script type="text/javascript">
var formdata = false;
(function () {
var input = document.getElementById("uploaded_file");
formdata = false;
formdata = new FormData();
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (formdata) {
formdata.append("uploaded_file[]", file);
}
}
}, false);
}());
</script>
HOw can I get the form data information in php (like we do as $_FILES)
If you are not using cross domain call then you can call ajax like this:
$.ajax({
url: "sendmail.php",
async: false,
type:"POST",
data : {cotactname:name},
dataType: "json",
contentType: 'application/x-www-form-urlencoded',
success: function(html){
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
try to change your data sending for more https://api.jquery.com/jQuery.ajax/
data : {cotactname:name},
also try to check console for any error is post ok on that file or try with correct path of file
You are sending a string from ajax and getting value of variable.
Try this:
CHANGE
data : "cotactname="+name,
TO
data: {"cotactname" : name},

Ajax on success of another ajax doesn't work in ie

I do an ajax call to get a list of all elements, say Products and populate them in a table with checkboxes. Then I make another ajax call to get which products were already selected and select them. This works in all browsers except ie. Am I doing something wrong?
$.ajax({
url : "${product_category_url}",
data : {"orgID":"${globalOrganisation.id}"},
dataType : "html",
statusCode: {
401: function() {
$('.ui-tabs-panel:visible').html("${ajax_session_expired}");
}
},
success : function(data) {
$("#productCategoryContainer").html(data);
$.ajax({
url: "${get_taggedProd_url}",
data: {"questionnaireId":_questionnaireId},
dataType: "json",
success: function(data){
var productIds = data.products;
$.each(productIds,function(index,value){
var obj = $('input[name="'+value+'"]');
obj[0].checked = true
selectRow(obj[0]);
});
}
});
}
});
This is due to caching by IE.
Please try this
$.ajax({
url : "${product_category_url}",
data : {"orgID":"${globalOrganisation.id}"},
dataType : "html",
statusCode: {
401: function() {
$('.ui-tabs-panel:visible').html("${ajax_session_expired}");
}
},
success : function(data) {
$("#productCategoryContainer").html(data);
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
$.ajax({
url: "${get_taggedProd_url}",
data: {"questionnaireId":_questionnaireId},
dataType: "json",
success: function(data){
var productIds = data.products;
$.each(productIds,function(index,value){
var obj = $('input[name="'+value+'"]');
obj[0].checked = true
selectRow(obj[0]);
});
}
});
}
});
and if you need more details please look into this
The thing in this code that always screws me up is trying to get the check box selected. Make sure obj[0].checked = true actually works.

How to update js object type variable via ajax?

I have a javascript variable that is created in php
echo "var".$locallist."=".create_js_variable($locallist,$db2_list_all,'db2');
and it looks in html page source code like
var locallist={
'CARINYA':[['2011-08-24-09-22 - w','20110824092216w'],['2011-08-18-13-15','20110818131546']],
'COVERNAN':[['2011-03-02-12-28','20110302122831']],
'DAVID':[['2010-12-22-19-43','20101222194348'],['2010-12-08-14-10','20101208141035']]};
Now I want to update the variable on button click via ajax
jQuery.ajax({
type: 'get',
dataType: 'text',
url: url,
data: {
what: 'db2list',
t: Math.random()
},
success: function(data, textStatus){
locallist = data;
console.log(locallist);
}
});
and the ajax calls this php code (note that it's the same php function that is called)
if($what == 'db2list') {
$db2_list_all = get_db2_database_list();
echo create_js_variable($locallist,$db2_list_all,'db2');
}
Console.log reports that
before update the variable is an object
after update it is a text
How can I fix that? So my other javascript code works again?
Well, look at your ajax call:
jQuery.ajax({
type: 'get',
dataType: 'text',
url: url,
data: {
what: 'db2list',
t: Math.random()
},
success: function(data, textStatus){
locallist = data;
console.log(locallist);
}
});
Notice you've got the dataType as text? It's going to bring the data in and treat it as text. Try changing the dataType to 'json'. That will convert the data that was brought in to a regular 'ol object, just like what you already have.
Your AJAX-request has a type dataType: 'text',
Change it to JSON :)
Use dataType: 'json'.
jQuery.ajax({
type: 'get',
dataType: 'json',
url: url,
data: {
what: 'db2list',
t: Math.random()
},
success: function(data, textStatus){
locallist = data;
console.log(locallist);
}
});

JavaScript/jQuery Variable Scope Issue with Nested .ajax() calls

I'm having a difficult time passing the variable postData which is a serialized jQuery array object to a nested child .ajax() call. postData is passed successfully to the first .ajax() call, but when I attempt to use it in the second .ajax() call, it does not post any form elements, as the variable is undefined at that level:
$(".myForm").submit(function () {
var postData=$(this).serializeArray();
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./insertComment.php",
data : postData,
success: function() {
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./getComments.php",
data : postData,
success: function(comments) {
$(".Comments").html(comments);
}
});
}
});
return false;
});
I tried creating a second variable _postData attempting to perpetuate the variable on to the next .ajax() call, but it was unsuccessful (also tried var _postData=$(this).parent().serializeArray(); but I still wasn't able to perpetuate the variable):
$(".myForm").submit(function () {
var postData=$(this).serializeArray();
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./insertComment.php",
data : postData,
success: function() {
var _postData=$(this).serializeArray();
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./getComments.php",
data : _postData,
success: function(comments) {
$(".Comments").html(comments);
}
});
}
});
return false;
});
I tried implementing so-called JavaScript closure (something I still don't fully grok), but that led to more undefined variables and more failure:
$(".myForm").submit(function () {
var postData = function() {
$(this).serializeArray();
}();
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./insertComment.php",
data : postData,
success: function() {
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./getComments.php",
data : postData,
success: function(comments) {
$(".Comments").html(comments);
}
});
}
});
return false;
});
I tried searching around and tried implementing several other techniques, including jQuery traversal (.parent(), .filter(), etc.), but was unsuccessful. I know this is a common problem for a lot of folks, but so far I have not found a simple, understandable solution. Any suggestions would be greatly appreciated. Thanks!
Try this:
$(".myForm").submit(function ()
{
var postData=$(this).serializeArray();
$.ajax({ type : "POST",
async : false,
cache : false,
url : "./insertComment.php",
data : postData,
success: (function(pData)
{
// capture the posted data in a closure
var _postData = pData;
return function()
{
$.ajax({ type: "POST",
async: false,
cache: false,
url: "./getComments.php",
data: _postData,
success: function(comments)
{
$(".Comments").html(comments);
}
});
}
})(postData) // execute the outer function to produce the colsure
});
return false;
});
Here's what I ended up doing:
$(".myForm").submit(function () {
var postData = $(this).serializeArray(); // Gets all of the form elements
var myID = $(this.ID).val(); // Takes only a single value from the form input named ID
$.ajaxSetup({
data : "ID=" + myID // Sets the default data for all subsequent .ajax calls
});
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./insertComment.php",
data : postData, // Overwrites the default form data for this one instance only, including all form elements
success: function() {
$.ajax({
type : "POST",
async : false,
cache : false,
url : "./loadComments.php", // Notice there is no data: field here as we are using the default as defined above
success: function(comments) {
$(".Comments").html(comments);
}
});
}
});
return false;
});

Categories