Jquery query string type to - php

i am using serialize()
Some Event trigger(assume click)
var querydata= a=1&b=2&c=3 //jquery printing
$.ajax({
url: "script",
data: querydata,
method: "POST",
dataType: "text",
success: function(data) {
$("#counts").html(data);
}
});
in php do i just use the regular post method
a=htmlspecialchars($_POST["a"]); b=htmlspecialchars($_POST["b"]); and so on
or do i need to use jquery to get the string to variables and then send to data as a object array
if jquery is also an option could you tell me how i would do that im fairly new to jquery and i really want to learn it

Why bother creating a functionality that your browser+PHP provide already??
In your case, if you really have to send a raw string:
var querydata = 'a=1&b=2&c=3';
$.ajax({
url: "script",
data: querydata,
method: "POST",
dataType: "application/x-www-form-urlencoded",
success: function(data) {
$("#counts").html(data);
}
});
You may also want to simplify:
var querydata = {a: 1, b: 2, c: 3};
$.post('url', querydata, function(data){
$("#counts").html(data);
});

Related

How can I send post data with ajax in jquery when loading page?

When loading a page, I need to send with the post method information to show just the same time the information received
I have this as an example in jQuery:
$(document).ready(function(){
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});
The ready() event occurs when the DOM (document object model) has been loaded.
Since you want AJAX call to happen when document is loading move below code outside ready();
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
$(document).ready(function(){
var data = { "Boner": "Jams"};
$.ajax({
type: "POST",
url: "http://www.copypasta.org/postdatahere",
data: JSON.stringify(data),
success: function(){
alert("WOW A BONER!");
},
dataType: "json"
});
});
You are already using the right example just set the url,data and dataType variables
$(document).ready(function(){
var url="http://example.com/post.php";
var data={field1:"value1",field2:"value2"};
var dataType="text";
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});
as Jaydeep Mentioned you can also use the same example without .ready if you want ajax request to happen even if the page is still loading
var url="http://example.com/post.php";
var data={field1:"value1",field2:"value2"};
var dataType="text";
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Also another note
dataType is decided by the data you are expecting to receive not the data you are sending for plain text use "text" for JSON encoded date use "json"

why replaced plus in string by space

I am using ajax to send data through an AJAX call to set.php:
$.ajax({
url: "ajax/set.php",
dataType: "html",
type: 'POST',
data: "data=" + data,
success: function (result) {
alert(result);
}
});
Before sending the AJAX call, I am using JavaScript to alert() the data, the data is:
JeCH+2CJZvAbH51zhvgKfg==
But when I use $_POST["data"], the data is:
JeCH 2CJZvAbH51zhvgKfg==
Which displays pluses replaced with spaces, how can I solve this problem?
When using $.ajax, use an object rather than a string with the data: option. Then jQuery will URL-encode it properly:
data: { data: data },
If you really want to pass a string, you should use encodeURIComponent on any values that might contain special characters:
data: 'data=' + encodeURIComponent(data),
Taking a look at the jQuery docs, you can pass an object to data instead of the actual query built by hand. Try:
$.ajax({
url: "ajax/set.php",
dataType: "html",
type: 'POST',
data: {
data: data
},
success: function (result) {
alert(result);
}
});
I believe you need to encode that + with its URL Encoded value %2B.
To do this, use the replace method.
var data = data.replace(/\+/g, "%2B");

access the json encoded object returned by php in jquery

I want to post some data to php function by ajax, then get the encoded json object that the php function will return, then I want to get the information (keys and values) from this object, but I don't know how, here is my code:
$.ajax({
url: "functions.php",
dataType: "JSON",
data: {id: id},
type: 'POST',
success: function(json){
for(var i=0;i<json.length;i++){
alert(json['fname']);
}
}
});
and here is the json object returned:
[{"id":"1","fname":"kjhkj","mname":"kjhjh","lname":"lname","prefix":"Mr.","suffix":"jhkjhk","email":"hf#dd.com","image":"11281454_423648214427141_318277024_o.jpg","info":"hjgvhd"}]
Try:
$.ajax({
url: "functions.php",
dataType: "JSON",
data: {id: id},
type: 'POST',
success: function(json){
for(var i=0;i<json.length;i++){
alert(json[i].fname);
}
}
});
It is rather simple to do this:
var data = jQuery.parseJSON(json);
jQuery.each(data, function(i, item) {
jQuery('.derp').append(item.mname + "<br />");
});
Example
Reference
jQuery.each()
jQuery.parseJSON()

passing javascript object array to ajax

This is my imple code on submit of form. Where I want to insert table data values in database through ajax. But it's not going to controller.
$('#submit').click(function(){
var TableData = new Array();
$('#cart_details tr').each(function(row, tr){
TableData[row]={
"productname" : $(tr).find('td:eq(0)').text()
, "quantity" :$(tr).find('td:eq(1)').text()
, "unit" : $(tr).find('td:eq(2)').text()
, "unit_rate" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift();
//TableData = $.toJSON(TableData);
var TableData = JSON.stringify(TableData);
alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
When I stringify tabledata array output is like this..
[{"productname":"Copper Sulphate","quantity":"1","unit":"1","unit_rate":"100"},
{"productname":"Hypta Hydrate","quantity":"1","unit":"1","unit_rate":"100"}]
My question is why it's not going to controller? it's because of array object or something else??
Tabledata is javascript object array . Am I right??
Use
$.ajax({
instead of
$.post({
use this code
$.ajax({
type: "POST",
url:followurl,
data: {TableData : TableData},
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
check the Documentation jquery.post
The syntax for $.post is
$(selector).post(URL,data,function(data,status,xhr),dataType)
You don't have to define the type ,
but here you are using the $.ajax mixing with $.post
this is the $.ajax function syntax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
SO change the $.post to $.ajax and try
As you can read in the documentation, you can pass an object to data. I think you'd make things easier and simpler for you if you followed that approach.
...
//TableData = $.toJSON(TableData); NO!!!
//var TableData = JSON.stringify(TableData); NO!!!
//alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: {
dataTable: TableData
},
datatype : "json",
cache: false,
success: function (data) {
alert(data);
}
});
});
Very simple example (without validation or anything of the kind) of index.php/purchase/save_product
$data = $_POST["dataTable"];
echo $data[0]["productname"];// Sending back the productName of the first element received.
die();
As you can see, you could access data in your index.php/purchase/save_product file very easily if you followed this approach.
Hope it helps.
Hi It look like you are using some CMS or Framework. Can you please let us know which framework or CMS you are using. I would then be able to sort out this issue. It looks like you are using Code Ignitor. If its so then i hope this would help you
$.post( "<?php echo base_url();?>index.php/purchase/save_product", function(data) {
alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
})
in Your case your ajax call must look like
var followurl="<?php echo base_url();?>index.php/purchase/save_product";
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
Error Seems to be in your followUrl please try using as its in mine code

AJAX jQuery PHP Return Value

I am new to AJAX and am kind of confused by what PHP passes back to the jQuery.
So you have an AJAX function like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
(I took this from ajax another StackOverflow page.)
But on various other resources they will have the success section look like this:
success: function(data) {functionfoocommandshere}
I am just confused as to what dictates the naming of this variable? If the PHP ultimately echoes an array:
echo $myVar;
How can I get this from the AJAX?
An Ajax-Requests fetches a whole site. So you'll not get any data in variables, but the whole site in the data-parameter. All echos you made together will be in this parameter. If you want to retrieve an array, you should transform it to json before.
echo json_encode($myArray);
Then you can receive it via Ajax in this way
$.ajax({ url: '/my/site',
data: {action: 'test'},
dataType: 'json',
type: 'post',
success: function(output) {
alert(output);
}
});
In you PHP file, use json_encode to turn the array into a more convenient format for use in Javascript. So you would have something like:
echo json_encode($myArray);
Then, in your JavaScript, the data variable of the success method will hold the JSON. Use jQuery's parseJSON to convert this to a JavaScript object, which will then be very easy to manipulate. I don't know what you array contains, but you might do something like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.name[0] === "John");
}
});
Again, the data variable here will contain anything your PHP outputs, but JSON is a common and convenient way to transfer data back to your JavaScript.
<script type="text/javascript">
$.ajax({
url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
</script>
<?php
$action = $_POST['action'];
echo $action;?>
Any output that is printed/echoed will be returned to the success function. This is handy when you want to fill an html container with something that you need to run in real time.
Once you get the hang of this, another option is to use JSON to return variables with values.
The data that's returned from the PHP AJAX function, can be retrieved from the success block. Here's the manual
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
dataType: 'json',
success: function(output) {
//output is the data returned from PHP AJAX function in JSON format
alert(output);
}
});

Categories