Add key to hash if condition is true - javascript

I've got this code:
function myFunction(serializeData, extraSerializedData){
//serializeData is boolean
var formSerializedData = '';
if(serializeData){
var formSerializedData = $("#myform").serialize();
if (typeof extraSerializedData !== 'undefined'){
formSerializedData += extraSerializedData;
}
}
$.ajax({
type: "get",
url: "/123",
data: formSerializedData, //TODO!!!
success: function(data){
//......
I want to add the data key only if serializeData exists. Is it possible and how to do this in a way that the code remains "beautiful"?

I'd suggest, though untested:
$.ajax({
type: "get",
url: "/123",
data: serializeData !== undefined ? formSerializedData : null,
success: function(data){
//......
}
});

I hate ternary operators, so here, have this:
function myFunction(serializeData, extraSerializedData){
var formSerializedData = '';
var extendWith = {};
if(serializeData){
var formSerializedData = $("#myform").serialize();
if (typeof extraSerializedData !== 'undefined'){
formSerializedData += extraSerializedData;
}
extendWith.data = formSerializedData;
}
$.ajax($.extend({
type: "get",
url: "/123",
success: function(data){
//......
}
//rest of the object
},extendWith));
}

I would suggest use ajaxSetUp :
$.ajaxSetup({
url: "/123/",
type: "get",
success: function(){};
});
//Check for serializeData data and pass accordingly
$.ajax({ data: myData });

function myFunction(serializeData, extraSerializedData){
var ajaxthing = {
type: 'get',
url: '/123',
success: function (data) {...}
};
if(serializeData){
var formSerializedData = $("#myform").serialize();
if (typeof extraSerializedData !== 'undefined'){
formSerializedData += extraSerializedData;
}
ajaxthing.data = formSerializedData;
}
$.ajax(ajaxthing);

Related

Looping through two JSON arrays Ajax

I'm trying to get data from a Json file using the id from a previous previous ajax call looping through the the second array based on the id gotten from the first
I have tried
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
$('.blog').empty();
for (var i=0; i<n; i++) {
var storytitle = output.data[i].story_view;
var id = output.data[i].titleID;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var n2 = output2.data[0].episode_count;
for (var i=0; i<n2; i++) {
var titles = output2.data[i].title;
console.log(storytitle + " " + titles);
}
}
else {
console.log('faileds');
}
});
}
} else {
console.log('failed');
}
});
});
The storyTitle has a single value and loops through all the titles when i check my console.
I tried debugging and found out the second for-loop was only executed once, after executing request2.done, it goes back to the first for-loop after the first has finish all its loop, it executes the second for-loop.
I don't know where am missing it.I need help with this.
Finally solved the problem...Changed my code to...
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var CLASS = this.story_view;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
console.log(id + " " + id2);
})
}
})
})
} else {
console.log('failed');
}
});
})
And it worked fine....thanks to Swapnil Godambe

How to pass param between ajax calls

I am trying to pass param between two different ajax calls, the params only exist inside the ajax scope but not outside of it.
i saw the option of calling from the first ajax success section to another ajax and i don't want this, is their any other way?
my code
jQuery.ajax({
url: '/modules/products/ajax.php',
data: {
prod_id: prod_id,
act: 'get_selected_values_for_sub_cat'
},
type: 'POST',
async: false,
dataType: 'json',
success: function(data) {
var res = JSON.stringify(data);
res = jQuery.parseJSON(res);
var selected_array = [];
jQuery.each(res, function(key1, value1) {
selected_array[key1] = jQuery.parseJSON(value1);
})
}
});
console.info("selected_array", selected_array);
i try this
function ajax_get_selected_values_for_sub_cat() {
return jQuery.ajax({
url: '/modules/products/ajax.php',
data: {
prod_id: 123,
act: 'get_selected_values_for_sub_cat'
},
type: 'POST',
async: false,
dataType: 'json',
success: function(data) {
}
});
}
var re = ajax_get_selected_values_for_sub_cat();
res = JSON.stringify(re);
res = jQuery.parseJSON(res);
var selected_array = [];
jQuery.each(res, function(key1, value1) {
selected_array[key1] = jQuery.parseJSON(value1);
})
console.info("selected_array", selected_array);
what am i missing ?
thanks
ajax function returns an object that implements the promise interface. You can implement it like this:
function ajax_get_selected_values_for_sub_cat(id) {
return jQuery.ajax({
url: '/modules/products/ajax.php',
data: {
prod_id: id,
act: 'get_selected_values_for_sub_cat'
},
type: 'POST',
async: false,
dataType: 'json'
});
}
var promise = ajax_get_selected_values_for_sub_cat(123);
promise.done(function(re){
res = JSON.stringify(re);
res = jQuery.parseJSON(res);
var selected_array = [];
jQuery.each(res, function(key1, value1) {
selected_array[key1] = jQuery.parseJSON(value1);
})
console.info("selected_array", selected_array);
});
http://api.jquery.com/jQuery.ajax/#jqXHR
You can use callback methods as below-
function ajax_get_selected_values_for_sub_cat(successCallback)
{
jQuery.ajax({
url : '/modules/products/ajax.php',
data : {prod_id:123,act:'get_selected_values_for_sub_cat'},
type : 'POST',
async: false,
dataType: 'json',
success:function(data){
successCallback(data);
}
});
}
ajax_get_selected_values_for_sub_cat(function(re){
res =JSON.stringify(re);
res = jQuery.parseJSON(res);
var selected_array =[];
jQuery.each( res, function( key1, value1 ) {
selected_array[key1]=jQuery.parseJSON(value1);
})
console.info("selected_array",selected_array);
});

Jquery Ajax working on localhost (xammp) but not working on Server (cpanel)?

Jquery Ajax working fine on localhost (xammp) but not working on Server (cpanel) !
also ajax with Javascript working fine , but throught JQuery it has problem ! (on server)
i changed send method to POST but problem same.
this is my website :
concert20.ir
an this is js code:
var arr=[];
function func1(id,status){
var str;
var a=id.split('-');
// a[0] = chair number
// a[1] = singer id
// a[2] = place
length=arr.length;
if(status=='رزور شده')
{
// check that who resereved it?
var index=jQuery.inArray(parseInt(a[0]), arr);
if(index>=0)
{
// unreserved ...
//arr[index]=-1;
arr.splice(index, 1);
length=arr.length;
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({reservefunc:0,chairnum:a[0],singerid:a[1],place:a[2]}),
success: function(result){
$("#drawtable").html(result);
}
});
if(length==0)
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:0,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
else
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:1,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
}
}
else if(status=='قابل خرید')
{
// reserve ...
arr.push(parseInt(a[0]));
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({reservefunc:1,chairnum:a[0],singerid:a[1],place:a[2]}),
success: function(result){
$("#drawtable").html(result);
}
});
sts=$("input#checksts").val();
if(sts==-1)
{
var index=jQuery.inArray(parseInt(a[0]), arr);
arr.splice(index, 1);
alert('این صندلی قبلا خریداری شده است');
}
length=arr.length;
if(length==0)
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:0,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
else
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:1,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
}
}
UPDATE
i found the problem!
the server was context-sensitive and i did not observe it
i changed ServerReply.php to serverReply.php and it worked fine ...
try to write absolute url save to versions of ulr in var and comment , un comment respectively
var mainurl = "http://localhost/project/serverReply.php"
var mainurl = "http://xeample.com/project/serverReply.php"
try if it can solve the problem
Try this:
$.ajax({
type : "GET",
url : "ServerReply.php",
cache : false,
async : true,
global : false,
data : {
"showdetails":0,
"chairnum":arr
}
}).done(function(msg) {
//Do something
});

send json into php using jquery

I have a JSON from a PHP file and I want to send that output to another PHP file. This is my JavaScript:
var data_1;
$.ajax({
type:"POST",
url:"sd.php",
success:function(result){
data_1 = result;
test(data_1);
var st = JSON.stringify(data_1);
$.post('get.php',{q:st},function(data){
window.location = "get.php";
});
}
});
And my PHP file to store the JSON:
<?php
$obj = json_decode($_POST['q']);
echo $obj;
?>
But it outputs nothing. What should I do? Please help.
You may try this i wrote for you, but its not tested
/**
* Created by vladimirnikolic on 3/24/14.
*/
$('#submit').click(function(e){
e.preventDefault();
var form_data = $('#your_form').serializeArray();
var submit_data = serializedFormToDTO(form_data);
$.ajax({
url: 'sd.php',
type: 'POST',
dataType: 'json',
data: submit_data
})
.done(function(xhr) {
$.post("get.php", {
q: submit_data
},
function (data) {
// handle data here
// console.log(data);
}, 'json');
}
)
.fail(function(xhr) {
var response_text = $.parseJSON(xhr.responseText)
console.log(response_text);
})
});
function serializedFormToDTO (data, json) {
json = (typeof json !== 'undefined') ? json : false;
if ((json !== true) && (json !== false) ) {
console.log('invalid value of second parameter (should be true/false for json output)');
return false;
}
var result = {};
for (var i = data.length - 1; i >= 0; i--) {
result[data[i].name] = data[i].value;
}
if (json === true) {
result = JSON.stringify(result);
}
return result;
}
$.ajax({
url: 'sd.php',
type: 'POST',
data: JSON.stringify(data_1), // data_1 is a javascript object here
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(returned_data) {
alert(returned_data);
}
});

Getting the responseText of the function in jQuery/AJAX

function foo(dataString){
var jqXHR = $.ajax({
type: "POST",
url: "<?php echo site_url('c_device/check_empId'); ?>",
data: dataString,
dataType: 'json',
cache: false,
success: function(data){
console.log(data);
if(data.length == 0){
return 0;
}
else{
$("#error_"+tr_id).html("Emp id exists");
$("#"+tr_id).css("background-color","red");
return 1;
}
}
});
return jqXHR.responseText;
}
how can I get the returned responseText of foo?
using
(in another jQuery event)
var result = foo(dataString);
doesn't work.
result will still be undefined.
It is best to use callbacks for what you're wanting to do.
var uiHelper = function () {
var cachedText= {};
var getText = function (options) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="options" type="object">options{url:The url to the file with the HTML,successCallback:function,errorCallback:function,isAsync:true||false,cache:true|false}</param>
function xhrSuccess() {
if (this.cache) { cachedText[this.url] = this.responseText; };
if (this.successCallback) {
this.successCallback.apply(this.responseText, this.arguments);
} else {
return cachedText[this.url];
};
};
function xhrError() {
if (this.errorCallback) {
this.errorCallback.apply(this.statusText);
} else {
return this.statusText;
};
};
if (!cachedText[options.url]) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", options.url, options.isAsync);
xmlhttp.cache = options.cache || false;
xmlhttp.url = options.url;
xmlhttp.onload = xhrSuccess;
xmlhttp.onerror = xhrError;
xmlhttp.successCallback = options.successCallback || undefined;
xmlhttp.errorCallback = options.errorCallback || undefined;
xmlhttp.send();
} else {
if (options.successCallback) {
options.successCallback.apply(cachedText[options.url], this.arguments);
} else {
return cachedText[options.url];
};
};
};
return {
getText: getText
};
}();
-----Usage-----
var successCallBack = function () {
}
var errorCallBack= function () {
}
uiHelper.getText(
{
url: 'url',
successCallBack: successCallBack,
errorCallBack: errorCallBack,
isAsync: true,
cache: false
})
This is because ajax is asynchronous, therefore you cant simply do like that.
This issue can be solved in two ways
Passing a callback function
Using jquery's when
passing callback
function foo(dataString, callback){
var jqXHR = $.ajax({
type: "POST",
url: "<?php echo site_url('c_device/check_empId'); ?>",
data: dataString,
dataType: 'json',
cache: false,
success: function(data){
console.log(data);
if(data.length == 0){
return 0;
}
else{
$("#error_"+tr_id).html("Emp id exists");
$("#"+tr_id).css("background-color","red");
return 1;
}
callback (data);
}
});
}
using when
function foo(dataString){
return $.ajax({
type: "POST",
url: "<?php echo site_url('c_device/check_empId'); ?>",
data: dataString,
dataType: 'json',
cache: false
});
}
$.when (foo (dataString)).done (function(data){
console.log(data);
if(data.length == 0){
return 0;
}
else{
$("#error_"+tr_id).html("Emp id exists");
$("#"+tr_id).css("background-color","red");
}
secondMethod (data);
});
Hope this helps
I just added
async: false
in AJAX so it will be SJAX.

Categories