Passing array through ajax - javascript

I'm fairly new to the jQuery execute on the same page stuff. So far I have been passing only single values trough ajax which is working fine. Now, I need to pass an array which is created by checkboxes through ajax.
My form html, dynamically created by php:
<input type=checkbox class=box name=box[] value=".$row['DoosID']." />
My jQuery:
var BackorderDate = $("#BackorderDate").val();
var Box = $(".box").val();
if( (TerugleverDatum == "") ){
$("#backorderresult").html(" * Some Error .").fadeIn("Slow").fadeOut(3000);
} else {
$("#backorderresult").fadeOut();
$.ajax({
type :'POST',
url :'./backorder.php',
data : box : Box,
backorderdate: BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
}
My PHP:
$boxlist = json_encode($box);
foreach($boxlist as $boxvalue){
// Do something with every value
}
this gives me a javascript error on submit saying box is not defined.

change this:
data : box : Box, backorderdate: BackorderDate, // invalid way of sending
to this:
data : {box : Box, backorderdate: BackorderDate}, // valid way
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs.
More Info

Why don't you try enclosing all the data values in a open and close curly braze( { and } ) .
Else it will conflict with the syntax of $.ajax method.
I think it is causing the problem.

You are sending data value in wrongly manner -
The data property should always be a JavaScript object. It's properties are serialized into a regular query string (for GET requests), or a normal post body parameter string (for POST requests). This serialized string is then sent to the server, along with the AJAX request.
On the server you can read the properties of the data object as if they were sent as simple request parameters, via either GET or POST. Just like if the properties had been fields in a form.
Try this :
$.ajax({
type :'POST',
url :'./backorder.php',
data : 'box='+Box+'&backorderdate='+BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
For more information see jQuery Ajax

You might want to refer to the php file like this: url :'../backorder.php' (double dots). At least, that's how I do it always.

Related

how to prevent my ajax parameter from holding php 'header()' value

I want to create a client-side and server-side check. These checks will look for empty names, invalid names, already taken names etc.
however my problem: my parameter is given the argument of the header, and therefore the user won't be redirected, it will only show code.
quick example:
$.ajax({
url: 'signup.php',
type: 'POST',
data: data,
success: function(response) {
window.location.href = response;
}
});
PHP code:
if(empty($loginName)) {
header('Location: index.php?loginName=empty');
exit();
}
So what I would like to have, but won't work (this is to give you an idea of what I am trying to do):
if(empty($loginName)) {
index.php?loginName=empty //and this should be the response argument
header('Location: index.php?loginName=empty');
exit();
}
My response parameter would have the argument of the header + the header content, so it will only generate html code. (I used console.log() to see what response held as argument). I can however take away the header tag and just use a string, my response will work then, but what I would like to have is the following: I would like to keep the header() function, but I want my response to redirect me correctly based on what the header() content is.
I already tried using a string and the header() function seperately, but this didn't work, unfortunately.
So expected result would be (if loginName were to be empty) that response holds a string with: index.php?loginName=empty, but without removing the header() function.

Passing multiple arguments through HTTP GET

I have an HTML file referencing a PHP script to perform various functions. One of the ways the HTML file calls the PHP script is through an HTTP GET. The GET request should pass three parameters and return a list of all saved events as a JSON-encoded response.
So far, I have the following but I'm not sure how to pass the three arguments through the HTTP GET. Also, I'm not sure if I am returning the JSON-encoded response correctly:
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo json_encode(events.json); }
GET requests are done through the URL... So if you want to pass three GET requests you would do...
http://www.domain.com/target.php?param1=whatever&param2=whatever&param3=whatever
target.php represents the PHP script file you want to send the information to. You can have as many variables as you want but just keep in mind that every other GET request has to be separated by an & symbol. The first param simply has to be started off with a ? symbol.
If you want to use Javascript, I would recommend using JQuery. You can do something like this
$.get('target.php?param1='+whatever+'&param2='+whatever2, function(data) {
alert(data);
});
Or you can use window.location to send a link with the appropriate link above.
If you want to use AJAX specifically, here is a way of doing it with JQuery (there are ways with Javascript that I could update later if necessary:
$.ajax({
type: "GET",
url: "http://www.domain.com/target.php",
data: { param1 : "whatever", param2 : "whatever", param3 : "whatever" },
success: function(result){
//do something with result
}
})
If you want to access the variables, you can call $_GET['param1'] or $_REQUEST['param1'] to get access to them in PHP. Simply change the name in the brackets to the desired variable you want and store it in a variable.
If you want to access the params with Javascript... well the most efficient way is to go and decode the URL that was used and pull them out. See here
Hope this helps!
You can access the parameters from the URL via the $_GET superglobal in PHP.
For example, if your URL is http://example.com/test.php?param1=foo&param2=bar, then you could access them in PHP like so:
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
See http://www.php.net/manual/en/reserved.variables.get.php for more details.
As for returning a valid JSON response, you can check out this answer. It uses PHP's header function.

How can I iterate this json?

"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there

Use and meaning of data: { get_param: 'value' } in jQuery ajax + JSON

I am parsing generated json with jquery $.ajax but there is one option that I dont understand. I saw it in some examples and tried to look for at jquery.com but still not sure about it:
this option is:
data: { get_param: 'value' }
which is used like this:
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' }, //why we shell use that in that case?
success: function (data) {
var names = data
$('#cand').html(data);
}
});
I know that "data:" is what sent to the server but parsing JSON I thought i don't send but retrieve from server with GET type. And the next part "get_param: 'value'"
does not make sense to me in that case either, could anyone please explain when and what for and in what cases it shell be used?
thank you.
I know that "data" is what sent to the server
Yes. If data is an object, it gets serialized to an application/x-www-form-urlencoded string and then placed in the query string or request body as appropriate for the request type (GET/POST).
jQuery does all the escaping necessary for this.
(It also, by default, collapses nested data structures (you don't have any in your example) into PHP-style by adding [] to key names).
but parsing JSON
JSON is not involved (unless the server responds with some).
when and what for and in what cases it shell be used
Whenever you want to pass data to the server rather than requesting a static URI.
You don't send JSON (usually), you send simple GET or POST HTTP parameters. They are given to the ajax method in an object literal usually, but you could have used the string "getparam=value", too. If you provide an object, jQuery will do the parameter-serialisation and URL-encoding for you - they're sent as x-www-form-urlencoded.
To cite from the docs:
data (Object, String)
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting.

pass array and individual string to php file using ajax call

I try to implement the following code
var flag = new Array();
var name = $("#myselectedset").val();
$.ajax({
type: 'post',
cache: false,
url: 'moveto.php',
data: {'myselectset' : name,
'my_flag' : flag
},
success: function(msg){
$("#statusafter").ajaxComplete(function(){$(this).fadeIn("slow").html(msg)});
}
});
You can see that the name is a single string and the flag is an arry, am I using the right format for passing them throw ajax call, anyone could help me, thanks
It is impossible to pass arrays in a POST request. Only strings.
You will either need to stringify your array, or consider posting as JSON instead.
You should be able to do something quite simple, like replace your "data" property with:
data : JSON.stringify( { myselectset : name, my_flag : flag } )
That will convert the data into a JSON string that you can turn into PHP on the other side, using json_decode($_POST["my_flag"]);
Very important note:
For JSON.stringify to work, there can't be any functions in the array - not even functions that are object methods.
Also, because this is a quick example, make sure that you're testing for null data and all of the rest of the best-practices.

Categories

Resources