How to pass multiple array values in ajax url - javascript

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);
}
}
});
}

Related

How do i split ajax return values using jquery

I want to split the ajax returned values using jQuery.
Here is my code:
var url = "/StudentProgress/GetStudProgDet/";
$.ajax({
url: url,
data: { currentAcadYr: iAcademicYearText, currentSem: iSemesterText },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (data) {
var result = $(data).text().split(':');
var ProgAcadYearCode = result[0].ProgAcadYearCode;
var productSize = result[1];
// alert(data.ProgAcadYearCode);
//$("#ToProgressAcademicYearId option").filter(function () {
// return this.text == testsem;
//}).attr('selected', true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
I got a result like this:
data = {
success: true,
progAcadYearCode: 20172018,
progAcadYearId: 17,
progressSemId: 47,
progressSemNo: 2
}
How do I extract the desired values from the JSON using jQuery?
Based on data what you shown,you have to directly fetch it's properties like below:-
success: function (data) {
console.log(data.success);
console.log(data.progAcadYearCode); //and so on
},

I am struggling to pass data to controller through Ajax

Trying to hit DeleteJobQuote controller through Ajax but no luck. Please guide me if anyone has any idea about it. The code seems OK but not able to do so. I am writing this code to delete a particular record from database.
Controller
[HttpPost]
public ActionResult DeleteJobQuote(int jobQuoteid)
{
using (var db = new KeysEntities())
{
var delJob = db.JobQuote.FirstOrDefault(x => x.Id == jobQuoteid);
if (delJob != null)
{
delJob.Status = "Delete";
db.SaveChanges();
return Json(new { success = true, Message = "JobQuote SuccessFully Deleted!" });
}
else
{
return Json(new { success = false, Message = "Delete UnSuccessFul " });
}
}
}
And JavaScript and Knockout code for this
self.deleteJobQuote = function (jobQuote) {
debugger;
$.ajax({
url: '/Companies/Manage/DeleteJobQuote',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function (result) {
if (result.success) {
$('#jobQuoteDeleteModal').modal('show');
}
else {
alert("You can not delete this record !!");
}
}
});
};
Change "data : ko.toJSON(this)" to "data: JSON.stringify({ jobQuoteid: 1 })". I have hardcoded jobQuoteid value to 1. Get it from jobQoute object.
complete code:
$.ajax({
url: '/Companies/Manage/DeleteJobQuote',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ jobQuoteid: 1 }),
contentType: 'application/json',
success: function (result) {
if (result.success) {
$('#jobQuoteDeleteModal').modal('show');
}
else {
alert("You can not delete this record !!");
}
}
});

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

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);
}
});

Handling Multiple JSON Objects

If I have a function like this, i pass in a variable of movieid.
function getFilmDetails(movieid) {
var filmDetails = 0;
$.ajax({
dataType: "json",
type: 'get',
mimeType: "textPlain",
url: 'http://api.themoviedb.org/3/movie/' + movieid,
async: false,
success: function(result){
if(result.popularity > 10000) {
result.popularity = 10000;
}
if(result.popularity < 0.1) {
result.popularity = 0.1;
}
filmDetails = result;
}
});
return filmDetails;
}
I'm calling over 100 films details through this function and as you can imagine, it takes forever to load the page by doing it this way. I need to easily access the values in the JSON for each film. For example:
alert(getFilmDetails(12345).description);
alert(getFilmDetails(65432).popularity);
alert(getFilmDetails(12345).tagline);
Is there a better way to do this?
// receive a callback------------v
function getFilmDetails(movieid, callback) {
var filmDetails = 0;
$.ajax({
dataType: "json",
type: 'get',
mimeType: "textPlain",
url: 'http://api.themoviedb.org/3/movie/' + movieid,
// async: false, // YUCK! Commented out
success: function(result){
if(result.popularity > 10000) {
result.popularity = 10000;
}
if(result.popularity < 0.1) {
result.popularity = 0.1;
}
callback(result) // invoke your callback
});
return filmDetails;
}
// make a callback
function workWithData(data) {
alert(data.description);
}
// pass the callback
getFilmDetails(12345, workWithData);

Categories