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);
}
});
Related
I have multiple values, I am trying pass all values in url to controller class at one time.
But last value passed in url.
function submitFormData(formData) {
var x = [];
for(var i = 0;i < formData.length ;i++ ){
alert(i);
x = [];
x.push(formData[i].name);
x.push(formData[i].email);
x.push(formData[i].message);
}
var url= '/userrecords?x='+x;
alert(url);
$.ajax({
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
beforeSend: beforeSendHandler,
url: url,
success: function(result){
if(result.success == true) {
$('.alert-success').show();
$('.alert-danger').hide();
$("#successmsg").html(result.msg);
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
} else {
$('.alert-danger').show();
$('.alert-success').hide();
$("#error").html(result.msg);
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
}
});
}
controller class
#RequestMapping(value = "/userrecords")
public #ResponseBody StatusResponse saveList(#RequestParam(required = false) String x,Model model)
throws ParseException, SQLIntegrityConstraintViolationException {
//read all values here
}
What is wrong in my code. And how to read all values in controller.
Convert your array output in JSON and send it to using AJAX and also you have to define content type is JSON.
you can also use jquery ajax it is very simple for request response.
$.ajax({
type: "POST",
dataType: 'json',
url:"URL here",
success: function(data) // response
{}
});
I think you should post your formdata as ajax data as below.
Pass your x veriable as a ajax data.
function submitFormData(formData) {
var x = [];
for(var i = 0;i < formData.length ;i++ ){
alert(i);
x.push(formData[i].name);
x.push(formData[i].email);
x.push(formData[i].message);
}
var url= '/userrecords';
alert(url);
$.ajax({
type: 'POST',
data: x,
cache: false,
processData: false,
contentType: false,
beforeSend: beforeSendHandler,
url: url,
success: function(result){
if(result.success == true) {
$('.alert-success').show();
$('.alert-danger').hide();
$("#successmsg").html(result.msg);
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
} else {
$('.alert-danger').show();
$('.alert-success').hide();
$("#error").html(result.msg);
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
}
});
}
I'm trying to send a POST dinamically in a javascript code to a PHP script.
It seems to me that there is something wrong that the data are not sending json data as parameters.
Here is how I generate de json data:
query_string_fn = {};
query_string_fn ["cdinterno"] = cdinterno;
o.row.find("input, select").each(function() {
var val = $(this).val();
var id = $(this).attr('name');
query_string_fn [id] = val;
if (id == 'cdfornecedor_new') {
var cmbSelected = $(this)[0];
value_label = cmbSelected.options[cmbSelected.selectedIndex].text;
} else if (id == 'cdtipo_new') {
var tipocmbSelected = $(this)[0];
tipovalue_label = tipocmbSelected.options[tipocmbSelected.selectedIndex].text;
} else {
$(this).val(val);
}
}).end();
if (value_label.length > 0)
o.row[0].innerHTML = value_label;
if (tipovalue_label.length > 0)
o.row[11].innerHTML = tipovalue_label;
editarFN_Post(query_string_fn);
Here is how I'm sending the data to php. There are some tests commented that I have tested:
function editarFN_Post(query) {
query["action"] = 2;
var data = query;
$.ajax({
type: "POST",
dataType: "json",
url: "funcoesFN_Fornecedor_Produto_post.php",
//processData: false,
//contentType: "application/json; charset=UTF-8",
//contentType: 'application/json; charset=UTF-8',
//data: data,
//data: data.toString(),
data: JSON.stringify(data),
//data: {data: query},
success: function(rsp) {
alert ("Success!");
alert (rsp);
},
failure: function(rsp) {
alert ("Failed...");
alert (rsp);
}
});
}
Here is the PHP code that I check if the parameters have been sent:
header("Content-type: application/json; charset=utf-8");
echo "action=" . $_POST["action"] . "<br>";
foreach ($_POST as $key => $value)
echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
var_dump($_POST);
None of these tests above return data.
Thanks!
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
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.
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);