parsing JSON inside of ajax sucess function - javascript

I am trying to parse and display this JSON data that gets returned. Basically I have an ajax call which reads an input, sends it via POST to a PHP page and the php page var_dump's the array which contains the data.
array(1) {
[0]=>
string(21) "jsmith#yahoo.com"
}
My AJAX Call looks like..
<script>
function searchDB()
{
var lookupemail = $('#lookupemail').val();
$.ajax({
type: "POST",
url: "includes/dbsearch.php",
data: {wordpress: lookupemail},
success: function(server_response)
{
var response = server.response.1;
alert(response);
}
});
}
</script>
How do I retrieve the string that is returned and assign it to a javascript variable?

Your PHP code would have to output JSON in the first place:
$array = array('jsmith#yahoo.com');
echo json_encode($array);

To make it into an array in JavaScript you can use
var newArray = $.map(server_response, function(el) { return el; });
However, you can access the JSON directly using the json_encode in PHP.
json_encode($phparray);
and then...
server_response.arraykey

Related

Php-Ajax-JS Multiple Data Returns Problem

i have a problem.I am waiting for your help.Thank you
index codes are here.Even if i write dataType:JSON it didn't work.
index.php
function referansButon(sayfaNo)
{
$.ajax({
url:"ajax.php",
type:"POST",
data:"action=referansButon&referansSayfano="+sayfaNo,
success:function(data)
{
var result=$.parseJSON(data);
alert(result[0]);
alert(result["referanslar"]); // i know they are the same but i just wanted to see it if it
//is working
}
});
}
ajax.php
$referanslar="sdfdsfds";
$sayfalar= "sdfsdfdsfds"; //just for trying values.
$array=array("referanslar"=>$referanslar,"sayfalar"=>$sayfalar);
echo json_encode($array);
data is a string which is returning from $.ajax you convert the string to json and store in var result and after that you are using data again which is still string. update your code
var result=$.parseJSON(data);
and for first obj
alert(result.referanslar);
And for second obj
alert(result.sayfalar);
instead of [0] & [1]

Transferring hash maps over ajax and converting to php array

I'm making an interpreter for a mini language, and I'm storing related information in hash maps. I'm convering those hash maps with JSON stringify, to send them over via ajax to the server side.
This is is the post-JSON stringify code I'm sending over to the server side:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
On the server side, how could I easily make a php array out of the "kv":["24","23","20"] bit without searching for certain characters?
Before sending it over ajax the output of json array is:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
After receiving it, the data is:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
after the htmlspecialchars_decode function, it becomes:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
json_decoding that gives me null
The ajax code:
function addValues(jsonArray) {
alert(jsonArray);
$.ajax({
url: 'insertTree.php',
type: 'POST',
data: 'dataToReceive=' + jsonArray,
success: function(data) {
//called when successful
alert(data);
window.location.reload();
},
error: function(e) {
//called when there is an error
console.log(e.message);
}
});
}
the php receiving code:
$dataReceived = htmlspecialchars(strip_tags($_POST["dataToReceive"]));
$dataRefined = htmlspecialchars_decode($dataReceived);
$var = json_decode($dataRefined, true);
var_dump($var['kv']); //null
Use json_decode to get the value. Since your base string isn't valid JSON, I massaged it a bit to get it to be
$string = '{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}';
$data = explode('|', str_replace('},{', '}|{', $string));
foreach($data as $str) {
$var = json_decode($str, true);
if(isset($var['kv'])) var_dump($var['kv']);
}

How to parse json object datalist in ajax sucess using javascript

i am trying to parse json datalist in ajax success bt it couldnot work. i have passed object containing list of data using json from controller to view,i help to parse json object in ajax success. i have attached my code below.
//return json object from controller
PurchaseDetails pd = new PurchaseDetails();
foreach (DataRow dr in dt.Rows)
{
pd.serialList.Add(new SerialInfo {
Machine_serial_no = dr[0].ToString(), macAddress = dr[1].ToString(), isMacPresent = _TD1.CheckMac(machineTypes_MTId),brandName=obj.brandName,machineName=obj.machineName,MachineModel=obj.MachineModel,modelId=modelId,machineId=obj.machineId,brandId=obj.brandId});
// pd.macaddressList.Add(new MacAddressInfo { MacAddress = dr[1].ToString() });
}
}
}
return Json(new {pd}, JsonRequestBehavior.AllowGet);
return Json(new {pd}, JsonRequestBehavior.AllowGet);
// my ajax code
$.ajax({
url: "/Import/ImportPurchase",
type: "POST",
data: function () {
var data = new FormData();
data.append("file", jQuery("#file").get(0).files[0]);
data.append("machineTypes_MTId", jQuery('#machineTypes_MTId').val());
data.append("modelId", jQuery('#searchValue').val());
data.append("modelName", jQuery('#searchid').val());
return data;
}(),
dataType:"JSON",
contentType: false,
processData: false,
success: function (data) {
alert(data.Machine_serial_no)
Your controller method is returning
return Json(new { serialObj = pd}, JsonRequestBehavior.AllowGet);
which is an object containing a name serialObj
So in the ajax success call back, you would need to access it using
success: function (data) {
var PurchaseDetails = data.serialObj;
Since PurchaseDetails contains a collection named serialList which is a collection of SerialInfo, then to access the value of the first Machine_serial_no, it would be
var serialNo = data.serialObj.serialList[0].Machine_serial_no;
However it would be easier to just use
return Json(pd, JsonRequestBehavior.AllowGet);
If you then want to access each Machine_serial_no property in the collection, use
success: function (data) {
$.each(data.serialList, function(index, item) {
var serialNo = item.Machine_serial_no;
you can use jQuery.parseJSON() to parse ajax response to JSON.
but seeing from your code, seems the response should already be in JSON because dataType parameter is already set to "JSON".
try this:
remove "()" after the ending bracket of function in "data" parameter.
try to console.log(data) and look at the response from your browser console,
the response might not be a valid json string.
If you are looking for convert js array to JSON then just use JSON.stringify() function. This will convert your JS variable data value to JSON format.
You can more find here.

Convert JavaScript object to JSON and POST it

I have to parse my html from and POST it to another script. When I use JSON.stringify to serialize object with parsed data, $_POST array in the receiving script is empty:
$("#addQueryForm").submit(function(event){
event.preventDefault();
result = {}
result['kindArr'];
result['factor'];
$("[rel=my-form]").each(function() {
result[$(this).attr("name")] = $(this).attr("value");
});
var form = JSON.stringify(result);
$.post("add_kind.php", form , function(data) {
alert(data);
//data shows me that $_POST array is empty
});
});
But if I write json string into the query manually, it would be correct:
$.post("add_kind.php", {"kind":"Var1","kindArr":"Var12345","factor":"Var0","synonym1":"Var1","synonym2":"Var2","synonym3":"Var3"} , function(data) {
alert(data);
//data shows me that $_POST contains posted data
});
What am I doing wrong?
P.S: stringify was excess.
Maybe serialize would be better in your situation:
var form = $(this).serialize();
$.post("add_kind.php", form, function(data) {
alert(data);
});

Passing a javascript array to a php page using post method

I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.

Categories