Ajax Call in PHP and jQuery - javascript

This is my functions.php script containing the following code. The array is encoded into JSON.
functions.php
$final['custom']['main'] = queryCustom($conn, $id);
echo json_encode($final);
My global.js has the following code which makes an AJAX request in jQuery:
$.ajax({
type: "POST",
url: "functions.php", // file to reach Ajax call
dataType: "json",
data: {
action: 'custom',
id: id,
},
success:
function(data) {
setCustom(data.custom);
I want to know what the data contains in function(data)? The setCustom(data.custom), what does this mean here? Can someone provide me an explanation of this please?

data contains an object literal provided by the server side json_encode(). It's been automatically parsed because the data type is set to json.
example:
PHP:
$final['custom']['main'] = queryCustom($conn, $id);
echo json_encode($final);
Will give the following json string (formatted for better understanding):
{
"custom": {
"main":[
{
"symbol":"MAP4",
"official_ID":"112315"
}
]
}
}
The ajax call above is set to datatype json. jQuery knows if this datatype is set, it will automatically parse the string to an object literal.
Javascript:
$.ajax({
type: "POST",
url: "url.php", // file to reach Ajax call
dataType: "json",
success: function(data) {
var main = data.custom;
console.log(main); // returns the child object with "main"
}
});
data contains the initial object, custom is a child object of data and main is a child object of custom.

Success: A function to be called if the request succeeds. The function gets passed three arguments:
Data Returned From The Server
Status
jqXHR (XMLHttpRequest Object)
In your PHP code you've added echo json_encode($final); which will be returned if the request is completed successfully. The response will be passed to data which you can later use in your front-end code.
You can read more about $.ajax() at http://api.jquery.com/jQuery.ajax/

Related

How can I return an array and HTML data in an AJAX response?

I have an array like this in my PHP page named new1.php:
$arr = ['value 1', 'value 2', 'value 3'];
$html = '<div>huge data with all tags like a page</div>';
$response = json_encode('array' => $arr, 'html' => $html);
echo $response
In the calling page, when I console.log(data.html) it gives undefined. The same happens for console.log(data.array);. Here is my AJAX code:
$.ajax({
url: "new1.php",
type: "POST",
data: { somedata: somedata },
dataType: "text",
success: function(data) {
console.log(data);
console.log(data.html);
console.log(data.array);
}
});
Most importantly, I want to know what is the best way to return a page with other data from AJAX response?
from your php code where you do json_encode add this to the top of the page
header("Content-Type: application/json");
then your encode should take in array as parameter instead
json_encode(array("array"=>$arr, "html"=>$html));
it should see your record as json now and please change ur dataType to json from Jquery intelligence guess from the server state (jquery) it will automatically take json instead
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
You should be json parse, because you are json encoding from php file, and as there is data type of your ajax is text so you need to parse the json.
$.ajax({
url:"new1.php",
type:"POST",
data:{somedata:somedata},
dataType:"text",
success: function(data){
data = JSON.parse(data);
console.log(data);
console.log(data.html);
console.log(data.array);
}
});

Ajax Request Sending Multiple Items/Javascript Object to Java

At first I was sending data over as one singular object like so:
function ajaxCall(){
$.ajax({
url: "someURL",
data: data,
type: "POST",
dataType: "json",
//more ajax stuff
});
$(document).ready(function() {
$("#htmlForm").on('submit',function(e){
e.preventDefault();
data = $("#htmlForm").serialize();
ajaxCall();
});
});
And on the java back end I would receive my request parameters individually like so:
firstRequestParam,
secondRequestParam,
etc..
However, there is a new addition which looks like this:
function ajaxCall(jsonStuff){
$.ajax({
url: "someURL",
data: {data: data, jsonStuff: jsonStuff},
type: "POST",
dataType: "json",
//more ajax stuff
});
Now on the back end I get this:
firstRequestParam = data,
secondRequestParam = jsonStuff
What is the best way to get my individual request parameters back now that they are jumbled up and stored as the first property in the javascript object?
EDIT: This is not a duplicate. I understand how ajax works. I am able to send the data over properly in the javascript object. I am having trouble extracting the data on the java side since the data is now all wrapped up into one single request parameter instead of split up into multiple request paramaters. Previously if I had 3 fields text fields in the HTML form, if I did request.getParameter(paramName); they would come in as: field1, field2, field3. Now, if I do the same request.getParameter(paramName); I get: data, jsonStuff.

AJAX call to server side function in javascript?

I'm new to AJAX and I'm not too clear about how to use the format of the AJAX call
ex
$.ajax({
type: "POST",
url: "Default.aspx/function",
data: '{ searchBy: id }',
contentType: "application/json; charset=utf-8"
}).success(function (result) {
alert(result);
})
I have a function in the .cs file that should take in a string ID and return a list of all the objects that contain that ID.
I want to call this function in the javascript to check that the returned list is null (therefore the ID does not already exist) before inserting new objects into the database.
How could I go about doing this?
All the examples I see return a string from the server side function.
If you have control of the server-side endpoint, then return whatever you want to indicate no matches - an empty list, null, empty string, etc. Then in the success function check for that.
Note the dataType ajax parameter. That tells the ajax function how to format the response for you to consume. If you are expecting JSON to be returned, use dataType: json and in the success function check for an empty json array result.length === 0. In the case of null or empty string, use a dataType: text and check for result == "null" or result == "". Etc.
If you don't have control of server side then you will need to conform to whatever data it sends back to you. The dataType is still the key though.
[WebMethod]
public static int function(int Id)
{
return Id;
}
If you need use only ajax, the best option is XMLHttpRequest, is Vanilla JS and more fast.
If you decide use ajax with jquery the function is:
$.ajax({
type: "POST",
url: "Default.aspx/function",
data: { searchBy: id },
dataType: 'json',
success: function(result) {
// Do something
}
});
I've never done C#, but your url parameter must be a path to a file (e.g. url: Default.aspx). In your file, you should have the logic to handle the request and call the right function. This function will check the DB, and will print the result.
// inside Default.aspx
// 1- is there a POST parameter? If so, call foo()
public static string foo(string postParam) {
// check DB, process
Print(result)
}
Inside your success callback, check if null:
.then(function(result) {
if (result === null) // do stuff
})

Read PHP output from array with AJAX

My PHP is outputting data like this:
$data['full_feed'] = $sxml;
$data['other_stuff']= $new;
echo json_encode($data);
So, in my jQuery, I'm doing this.
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
console.log(data['full_feed']);
});
This comes back undefined. So does console.log(data.full_feed). I'm getting back from PHP a valid JSON object, but missing how I can "parse" it correctly.
Parse "data" parameter in response with jQuery.parseJSON function. Then use parsed.full_feed value. Like below:
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
data = jQuery.parseJSON(data);
console.log(data.full_feed);
});
You can do like #tilz0R said or for your example to work you need to tell the browser you are sending a json response. So need to set content type header like
header('Content-Type: application/json');
echo json_encode($data);
to see what the server is returning do console.log(typeof data). If its a string you need to parse it. if its an object, it is already parsed.
Also you can put dataType:'json' in your ajax call to let jquery know you are excepting a json response.

Posting JSON string to PHP page

Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.

Categories