Post array to PHP through ajax - php

I'm trying to post an array through ajax to php file on form submit.
<form action="echo.php" method="post">
<input name="qwerty[]" type="text">
<input name="qwerty[]" type="text">
<input type="submit"/>
</form>
Basically, I use this to post to php file:
function getlist(alt) {
$.ajax({
type:'POST',
url: 'markattlist.php',
data:{today:alt},
success: function(data){
$('#helloflist').html(data);
},
error:function (){}
});
}
Above is an example of what I'm trying to do. I've searched, but unable to find the solution to that. How can I post an array through ajax.

You can serialize the form data using data:$('#form').serialize() function and can send it using ajax or you can use JSON data type to send an array.
var Data = $('#yorFormName').serializeArray();
var JSONData = JSON.stringify(convertToJSON(Data));
$.ajax({
url: your_url,
type: "POST",
dataType: "json",
data: JSONData,
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response.status == 'success') {
// success logic
}
},
error: function () {
var errMsg = "Unexpected Server Error! Please Try again later";
}
});
Hope this will help you.

Instead of bothering how to send what you need, I advise you to use jquery serialize() method:
function getlist(alt) {
$.ajax({
type:'POST',
url: 'markattlist.php',
data: $("form").serialize(),
success: function(data){
$('#helloflist').html(data);
},
error:function (){}
});
}
And check on server-side with
print_r($_POST);

data: JSON.stringify({d:c}),
Encode it as json and decode it on the server:
$data=json_decode($_POST["data"]);

Related

ajax link json datatype call

I want to send the data via ajax to other page. I have isolated the problem. This is the code.
Thank you all for your help..But no effect..
updated code
It worked...
<script>
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
var size=123;
var itemname=123;
var potency=123;
var quantity=12333;
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
</script>
So I click the link,it navigates, to dd.php which has
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']));
echo $_POST['itemname'];
?>
I get Object Object as alert. What am doing wrong? Pls throw some light here..thanks you..
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault();
var data = {"box":1233,
"size":565,
"itemname":565,
"potency":876,
"quantity":234};
$.ajax({
url: "dd.php",
type: "post",
data: data,
dataType: "json",
success: function(data) {
if(console){
console.log(data);
}
},
error: function(data) {
if(console){
console.log(data);
}
}
});
});
});
few things to consider... you can post data as object..which is clean and easier to use
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
....
var dataString ={'box':box,'size':size,'itemname':itemname,'potency':potency,'quantity':quantity};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json", //<--- here this means the response is expected as JSON from the server
success: function(data) {
alert(data.itemcode); //<--here alert itemcode
},
error: function(data) {
alert(data);
}
});
so you need to send the response as json in PHP
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Here you are using querystring as sent in GET request.
If you want to send the data in same form, you can use this with GET request type:
$.ajax({
url: "dd.php"+dataString,
type: "get",
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
Or for POST request,you will have to put data in json object form, So you can use :
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
});
And put echo in your php code :
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Javascript alert shows [Object object] for object. You can see response using console.log or can use that key with alert.
For more information, refer jQuery.ajax()

How to decode a json object sent through jquery ajax method in php file?

This is the jquery ajax part in which i have sent json data to the php file.
$(function () {
$('form').submit(function () {
var fields = $(this).serializeArray();
var ans_json = JSON.stringify(fields);
console.log(ans_json);
$.ajax({
url: "results.php",
type: "POST",
data: ans_json,
dataType: "json",
success: function (result) {
console.log(result);
}
});
return false;
});
});
Now i want to use this json data sent to the php page.How can i do it? I have done it this way but it returns null.
<?php
echo json_decode('ans_json');
?>
I have a set of 10 questions which need to be answered. 3 questions were answered so got the below result.This is what i got in my console.
[{"name":"answer_9","value":"a"},{"name":"answer_10","value":"a"}] quizzes.php:14
null
You don't need to decode any JSON string at server-side if you encode properly your parameters.
You can use .serialize() to do the form serialization for you, and it's ready to send.
$(function () {
$('form').submit(function () {
var serialized = $(this).serialize();
$.ajax({
url: "results.php",
type: "POST",
data: serialized,
...
});
return false;
});
});
Your parameters will be available in your $_POST as in any normal POST request. For example,
$ninth_answer = $_POST["answer_9"];
You need to decode the POST variable. Currently you're decoding just a string which even isn't valid JSON.
<?php
$json_arr = json_decode($_POST['my_json'], true);
var_dump($json_arr);
echo "First name in json is:". $json_arr[0]['name'];
?>
and edit your javascript to reflect following:
This posts my_json parameter with your json as an value. This makes it easy for PHP to recieve it using $_POST.
$.ajax({
url: "results.php",
type: "POST",
data: {"my_json": ans_json},
dataType: "json",
success: function (result) {
console.log(result);
}
});
I suggest to read a little about those things:
http://api.jquery.com/jQuery.ajax/
http://ee1.php.net/manual/en/function.json-decode.php

Jquery ajax get request

I am new to jquery and php, I have two input fields, zip and city, the city shall output a value based from the zip that the user input. The jquery script shall call a URL: http://domain.com/city?zip.php="zip; so that zip.php will return an echo value that will output to the city input field.
I tried using ajax getXMLHTTP. some times it works but sometimes not
Please Refer to the following code snippet below:
<input type="text" id="zip_code" name="zip_code" />
<input type="text" id="city" name="city" />
<script type="text/javascript">
// Some Jquery code here for ajax get request to http://domain.com/city?zip.php
</script>
if you are using jquery the use $.ajax option instead of getXMLHTTP
function passzipvalue(zip)
$.ajax({
type: "GET",
url : 'http://domain.com/city.php='
data:"zip="+zip,
success: function(msg){
$("#formsData").html(msg);
}
});
}
something like this or
$.get('http://domain.com/city.php?zip='+zip,function (msg){
$('#formsData').html(msg);
});
if you want to populate it in some input fields use .val instead of .html
Use jQuery.get, documented here. In the success handler, use the data argument to populate the city input.
Sample:
$.get('http://domain.com/city.php?zip='+$('#IdOfZipInput').val(), function (data){
$('#IdOfCityInput').val(data);
});
Use jQuery AJAX. For example:
var zip = $('#zip').val();
$.get('http://domain.com/city.php?zip='+zip,function (data){
$('#city').val(data);
});
$.ajax({
url: 'http://domain.com/city.php?zip='+zip,
type: get,
success: function(data){
$("div").html(data);
}
});
use this data will be displayed
If its a constantly updating element then use jquery.post as ie caches the "get" results.
jQuery.post('call.php',{ action: "get"}, function (data) {
jQuery('#content').append(data);
});
FInd the tutorial here http://vavumi.com/?p=257
try to use the jquery ajax
$.ajax({
type: "POST",
url: 'sample/test.php',//your url
data: data,//data to be post
cache: false,
success: function(html) {
alert(html);//response from the server
}
});
$.ajax({
url: 'url',
beforeSend: function (xhr) {
//show loading
}
}).done(function (data, xhr) {
//hide loading
//success
}).fail(function (xhr) {
//hide loading
//error
});

jQuery ajax querying a PHP script

<html>
<head>
<title>Testing AJAX</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function init() {
$("#form1").submit(submitForm);
}
function submitForm() {
var paramValue = $("#param_input").val();
$.ajax({
type: "GET",
url: 'http//xxx.edu/xxx/autocomplete.php',
data: {
query: paramValue
},
dataType: "json",
complete: function(data){
alert(JSON.stringify(data));
}
});
}
// On page load
$(document).ready(init);
</script>
</head>
<body>
<form id="form1" name="form1_name" action="" >
<label for="find">Value</label>
<input type="text" name="param" id="param_input" />
<input type="submit" name="button" id="button" value="Find">
</form>
</body>
</html>
I really want to be able to query my PHP script (which returns a JSON via json_encode()) and use that JSON information.
Right now the alert box says this:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
So I'm doing something wrong. Any ideas? I'm all new to AJAX / jQuery.
EDIT: added dataType: "json" but that did not help - still returning wrong JSON stuff...
Use success in place of complete, as in success callback you will get your data. In complete you will get XHR object
Refer below script
function submitForm() {
var paramValue = $("#param_input").val();
$.ajax({
type: "GET",
url: 'http//xxx.edu/xxx/autocomplete.php',
data: {
query: paramValue
},
dataType: "json",
success: function(data){
alert(JSON.stringify(data));
}
});
}
Try passing a dataType param to jQuery's ajax.
For example:
$.ajax({
type: "GET",
url: 'http//xxx.edu/xxx/autocomplete.php',
data: {
query: paramValue
},
dataType: 'json',
complete: function(data){
console.log( data );
}
});
One of the benefits of jQuery's ajax interface is that you won't have to JSON.parse (or worse, eval) if you use the correct dataType flag.
You're nearly there just add dataType to your $.ajax call.
function submitForm() {
var paramValue = $("#param_input").val();
$.ajax({
type: "GET",
url: 'http//xxx.edu/xxx/autocomplete.php',
data: {
query: paramValue
},
dataType: "json",
complete: function(data){
alert(JSON.stringify(data));
}
});
}
Alternatively you can declare the return content to be json by declaring it within the http response header.
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
You would use the above if you were restricted to vanilla JS, it is possibly good practice to use it anyway.
If you intend to also send JSON data, then you have to stringify already the data sent to the server.
$.ajax({
type: "GET",
url: 'http//xxx.edu/xxx/autocomplete.php',
data: JSON.stringify({
query: paramValue
}),
dataType: "json",
complete: function(data){
alert(JSON.stringify(data));
}
});
you should add this javascript file to make sure the JSON parser exists:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
Looks like a cross domain call which will fail unless you use Jsonp or some hacks. You should look for hacks for cross domain call to work something like YQL
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-cross-domain-ajax-request-with-yql-and-jquery/

AJAX post not working

I'm using jQuery and Codeigniter to update the database via AJAX. The following code does not seem to do anything or send anything to my controller when the button is clicked...
jQuery:
$("#button_submit1").click(function(e) {
$.ajax({
type: "POST",
url: window.location.href,
dataType: "json",
data: $('#writereview_form').serialize() + '&ajax=true',
cache: false,
success: function(data) {
alert("yay");
//$("#writereview_box").fadeOut(1000);
}
});
return false;
});
HTML:
<form action="http://mysite.com/places/writereview/2107" id="writereview_form" method="post" accept-charset="utf-8">
...
...
<input type="submit" name="submit" value="Submit Review" class="button_submit" id="button_submit1">
Any ideas why the ajax data is not being sent?
In this case its better to bind to the 'submit' event on the form and then use preventDefault() to stop the HTML submission and use Ajax instead.
You should also use the form's action instead of window.location
$("#writereview_form").submit(function(e) {
var $this = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: $this.attr('action'),
dataType: "json",
data: $this.serialize() + '&ajax=true',
cache: false,
success: function(data) {
alert("yay");
//$("#writereview_box").fadeOut(1000);
}
});
});
Try withiut using window.location.href and giving url as url: "page.php",

Categories