Ajax post - Sent array as data to PHP - javascript

I need to pass a JSON array to to PHP, and receive it as $_POST['data']. This will contain my data through json_parse.
I got an error, no clue what happens here. The Ajax call throws the following error:
[object Object] parsererror SyntaxError: Unexpected token <
My code:
function testJson() {
var arr = { };
arr['action'] = "anaction";
arr['type'] = "atype";
$.ajax("test2.php", {
type: "POST",
data: JSON.stringify({ data: arr}),
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
$("#result").html(data);
},
error: function (a, b, c) {
$('#error').html(a + " " + b + " " + c);
}
});
More info: The error mentioned before is from error function call.
Edited based on suggestions and testing the function now works like this:
function testJson() {
var arr = { };
arr['action'] = "anaction";
arr['type'] = "atype";
$.ajax("test2.php", {
type: "POST",
data: {data : arr}, /* Stringify deleted and added an array there, i remove too a non needed json related stuff */
success: function (data) {
$("#result").html(data);
},
error: function (a, b, c) {
$('#error').html(a + " " + b + " " + c);
}
});
Now I'm recieving the array in post as expected.
Dilemma, boths answers helps in the solution of the problem .

Multiple issues here:
var arr = { }; defines an object whereas var arr = [ ]; defines an array.
The use as arr['action'] = "anaction"; implies, that it is an object and not an array although named so.
Usually, jQuery is doing the job internally:
$.ajax("test2.php", {
type: "POST",
data: { "data": arr} } // no need to stringify anything here ...
...

If you setting the dataType as 'json' in the ajax function, this means that the php file should return valid json. Use json_encode in your php file.

Related

Serializing Array, reducing it, and serving just the name and value of the inputs in the array to ajax post

I have a form pushing to Zapier. I serialize the inputs into an array and then reduce it. Here's the code I use:
$(function() {
$("#lead-gen-form").submit(function() {
const formInputSerializedArray = $(this).serializeArray();
const ajaxData = formInputSerializedArray.reduce((acc, { name, value }) => ({ ...acc, [name]: value }), {});
$.ajax({
url: "",
type: "POST",
data: { ajaxData },
dataType: "jsonp",
cache: false,
success: function(data) {
window.location = "../sent";
},
});
return false;
});
});
This results in this, which is including the name of the const and adding brackets around the name of the input, when all I really want to pull is the name of the input:
ajaxData[utm_campaign]: test
ajaxData[utm_term]: 12
ajaxData[utm_content]: comm
ajaxData[utm_medium]: email
ajaxData[utm_source]: sig
What I am looking to make it result in is:
utm_campaign: test
utm_term: 12
utm_content: comm
utm_medium: email
utm_source: sig
When data is serialized by Ajax as JSON, it will include the name of the object being passed in so that it will create correctly formed JSON. The anonymous object created by this data: { ajaxData } gets turned into '{ "ajaxData": { "utm_campaign": ... } }'
Simply remove the surrounding {} (use just data: ajaxData) and you will get the expected '{ "utm_campaign": ... }'

JSON Object always return undefined with AJAX

The JSON Object always return undefined in spite of the object contains data, i check it by using breakpoints in debugging
This is Action method in Controller:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
List<ComViewModel> comms = articleService.GetMoreComments(ArticleID, CommsCount);
return Json( comms );
}
and I also replaced the code in Action method to simple code like that but not work too:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
ComViewModel com = new ComViewModel
{
CommentContent = "cooooooooooontent",
CommentID = 99,
SpamCount = 22
};
return Json( com );
}
This is jQuery code for AJAX:
function GetMoreComments() {
$.ajax({
type: 'GET',
data: { CommsCount: #Model.Comments.Count, ArticleID: #Model.ArticleID },
url: '#Url.Action("GetMoreComments", "Comment")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var JsonParseData = JSON.parse(result);
alert(JsonParseData[0].CommentID)
alert(result[0].CommentID);
alert(result[0]["CommentID"]);
}
});
}
Usually you would have to parse your data if you need to alert it the way you have it. alert(result) should show data. If you need to access array of objects you must parse it first. Here is my example....
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
//PARSE data if you need to access objects
var resultstring = response.replace(',]',']');
var JsonParseData = JSON.parse(resultstring);
alert(JsonParseData[0].address)
});
That is wordpress ajax but its the same concept

Failed to load resource: the server responded with a status of 500 using Ajax

I know this question has been asked previously, but I cannot find out what is the exact problem with my code.
function viewcalldetails(obj) {
alert("clicked");
var id = $(obj).attr("id");
$(".style-table-tab input[type='text']").val('');
setTimeout(function () {
$('.preloader-circle').show();// or fade, css display however you'd like.
}, 1000);
$.ajax({
type: 'POST',
url: pageUrl+"/LoadCallDetails",
data: '{LeadID: "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: OnValuecall,
failure: function (response) {
alert(response.d);
}
});
}
function OnValuecall(response) {
$(".preloader-circle").hide();
$("#ctl00_ContentPlaceHolder1_lbrfullname").text(response.d.FirstName);
$("#ctl00_ContentPlaceHolder1_lbrphonenumber").text(response.d.MobileNo);
$("#ctl00_ContentPlaceHolder1_lbraddress").text(response.d.Address1);
$("#ctl00_ContentPlaceHolder1_lbrorganization").text(response.d.OrganizationName);
$("#ctl00_ContentPlaceHolder1_lblremail").text(response.d.PrimaryEmail);
}
Web Method:
public static UserAjax3 LoadCallDetails(string LeadID)
{
//System.Threading.Thread.Sleep(3000);
UserAjax3 oUserAjax = new UserAjax3();
//BD_CommonEmail[] ocall = BD_CommonEmail.GetEmailAll(Convert.ToInt32(LeadID)).ToArray();
BD_Leads[] ocall = BD_Leads.getCallDetails(Convert.ToInt32(LeadID)).ToArray();
if (ocall.Length == 1)
{
// oUserAjax.LeadID = oLeads.LeadID.ToString();
oUserAjax.LeadID = ocall[0].LeadID.ToString();
oUserAjax.FirstName = ocall[0].FirstName;
oUserAjax.MobileNo = ocall[0].MobileNo;
oUserAjax.OrganizationName = ocall[0].OrganizationName;
oUserAjax.Address1 = ocall[0].Address1;
oUserAjax.PrimaryEmail = ocall[0].PrimaryEmail;
}
return oUserAjax;
There are many things in question:
Where does "pageUrl" comes from?
You're awaiting a JSON result, but your method seems to return a normal object. Where do you convert to JSON?
Did you try running with a debugger in single-step mode trhough your web method?
Why is your web method static?

jQuery autocomplete using data pulled from SharePoint list using ajax REST

I need to add autocomplete to an input textbox. The data needs to be fetched from SharePoint using AJAX / REST.
This what I've done so far:
JS
var myData = [];
var requestHeaders = {
"accept": "application/json;odata=verbose"
}
$.ajax({
url: "https://my-URL/sites/RMA-GFPLC/_api/web/lists/GetByTitle('AD_DB')/items? $select=Title,Regional_x0020_Office,Commodity,Commodity_x0020_Year,StateLookUp/Title&$expand=StateLookUp",
type: 'GET',
dataType: 'json',
async: false,
headers: requestHeaders,
success: function (data) {
$.each(data.d.results, function (i, result) {
myData.push(result.Title);
});
myDataSource(myData);
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
function myDataSource(myData){
$('#myAutoCompleteSearch').autocomplete({
source: myData,
minLength: 3
});
}
So far my code is not working, and I'm getting "Uncaught TypeError: Cannot read property 'label' of null " error in my console. I;m wonder what am I doing wrong here? Thanks!
This error occurs when a source for Autocomplete function contains an element(s) with a null value.
Solution
Add the condition for checking if value is not null:
$.each(data.d.results, function (i, result) {
if(result.Title) {
myData.push(result.Title);
}
});
Jast insert your code in
$(document).ready(function () {
//your code here
}

Javascript 'Namespaces' and jQuery AJAX

I'm using the recommendations laid down here (http://www.odetocode.com/articles/473.aspx) to write a JavaScript AJAX webchat system using simulated Namespacing and prototyping.
In one of my prototype methods I'm calling the $.ajax method in jQuery. What I then want to do is pass the returned JSON data into a method inside my JavaScript webchat namespace.
The problem seems to be because I've created an instance of my JavaScript webchat, I can't directly call a method inside it because I need to address it through the instance.
The key part in the code below is
success: function(data, textStatus) {
this.GetUpdate_Success(data)
},
I'm thinking because we're inside the $.ajax() method, that this no longer refers to our WebchatV3 object.
The full JavaScript code is shown below:
/// <reference path="/JavaScript/jquery-1.3.2-vsdoc2.js" />
// Simulated 'namespace'
var AvonAndSomerset = {}
// Chatroom run time data
AvonAndSomerset.WebchatV3 = function(memberId, passcode) {
this.Members = new Array(); // Members in the chatroom
this.Questions = new Array(); // The questions queue in the chatroom
// Details about the current user
this.currentMember = new AvonAndSomerset.WebchatV3.Member(memberId, passcode, null, null, null, null, null);
// Set-up AJAX defaults
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
AvonAndSomerset.WebchatV3.prototype = {
// Get latest Member,Quetsion,Transcript and Room data from server
GetUpdate: function(StartUp) {
$.ajax({
url: "JSON.aspx/Members_GetChanges",
data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
success: function(data, textStatus) {
this.GetUpdate_Success(data)
},
error: function(result) {
alert('Members_GetChanges() failed: ' + result.responseText);
}
});
},
// Callback - on success of GetUpdate()
GetUpdate_Success: function(data) {
alert('The AJAX call was successful!');
},
// Does the MemberID exist in the local array?
Members_DoesExist: function(MemberID) {
alert('Searching for ' + MemberID);
alert(this.Members.length);
}
The easiest way to fix this is to create a variable that references this at the proper scope required. this and scope work differently in javascript then most languages, in this case it is referring to the object being passed into the function.
// Get latest Member,Quetsion,Transcript and Room data from server
GetUpdate: function(StartUp) {
//here
var self = this;
$.ajax({ url: "JSON.aspx/Members_GetChanges",
data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
success: function(data, textStatus) {
self.GetUpdate_Success(data)
},
error: function(result) {
alert('Members_GetChanges() failed: ' + result.responseText);
}
});
},
Try
success: function(data, textStatus) {
AvonAndSomerset.WebchatV3.GetUpdate_Success(data)
},
That may work.

Categories