Send and receive data in same ajax request with jquery - php

What is the best way to send data and receive a response dependent on that data?
Consider the PHP file used for the request:
$test = $_POST['test'];
echo json_encode($test);
I have tried unsucessfully to achieve this with:
$.ajax({
type: "POST",
dataType: "json",
data: '{test : worked}',
url: 'ajax/getDude.php',
success: function(response) {
alert(response);
}
});

Lose the quotes to pass the object:
$.ajax({
type: "POST",
dataType: "json",
data: {test : worked},
url: 'ajax/getDude.php',
success: function(data) {
alert(data);
}
});

Instead of this
data: '{test : worked}'
try
data: {"test" : worked} // Worked being your data you want to pass..
data: {"test" : "worked"} // Else enclose worked in quotes

The problem appears to be that you're submitting a string rather than a json object - change data: '{test : worked}' to data: {test : 'worked'}

Related

How can I use ajax result as a variable that I can print everywhere in a page

Here is my ajax code:
$("#to").change(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url();?>/index.php/sales/getPrice",
dataType: "html",
data: {'from' : $('#from').val() , to: $('#to').val()},
success: function(response){
//$(".location").html(response);
}
});
});
I want to use ajax result instead of 40. (below code attached).
e: {
price : 40,
category: 'Economy'
}
You want to use the data the ajax call returned? So you can use it in the success part:
$("#to").change(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url();?>/index.php/sales/getPrice",
dataType: "html",
data: {'from' : $('#from').val() , to: $('#to').val()},
success: function(response){
alert(respone.price);
console.log(response);
}
});
});
Use console.log(response); in the success function, to get the data in the developer console of your browser.
var result = '';
$("#to").change(function(){
$.ajax({
type: "POST",
async: false,
url: "<?php echo base_url();?>/index.php/sales/getPrice",
dataType: "html",
data: {'from' : $('#from').val() , to: $('#to').val()},
success: function(response){
result = response;
}
});
});
Now use that result where you want:
e: {
price : result,
category: 'Economy'
}

How to get ajax request in php?

$.ajax({
type: "POST",
url: "Check_Country.php",
data: "{Country_name: "+Country_name+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(html){
$('select#Section').empty();
$('select#Section').append('<option>Select</option>');
$('select#Section').append(html);
}
});
How do you detect Country_name in Check_Country.php file?
I am using
$_POST['Country_name'];
in php file but, the console says that it cannot find Country_name.
Try to use
data: "{Country_name: "+Country_name"}"
instead of
data: "{Country_name: "+Country_name+"}"
i.e. remove the trailing + sign.
In your code only one syntax is wrong
you have to change this code :-
data: "{Country_name: "+Country_name+"}",
into
data: {"Country_name": Country_name}
or
data: "Country_name="+Country_name,
please try this:-

Sending JSON data using ajax issue

I have the following code:
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: JSON.stringify(arr),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
The result is null. In the PHP side I have:
echo json_encode($_POST);
and
print_r($_POST);
But both are giving empty results (checked Firebug also).
You can also set the dataType in Ajax to specify the content type as follows.
var city='city name';
var age=10;
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data:"City="+city+"&Age="+age,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
and in cities/index.php you can get this data by follows
if($_POST){
$city=$_POST['City'];
$age=$_POST['Age'];
// and do with $city and $age what you want.
//for return anything thing to `json` use follows we pass $age back to ajax
echo json_encode($age);
}
I guess you don't need to stringyfy the data because data should be PlainObject or String but in your case you can simply write like below
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: arr,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
as documented in jquery official site https://api.jquery.com/jQuery.ajax/
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. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
The data option passed to $.ajax() must be either a simple object, that jQuery will transform into a string of the formatkey1=value1&key2=value2.. OR it should be a string of the form key1=value1&key2=value2...
In your case, it can be solved by passing the object itself and letting jQuery do the query string formatting:
$.ajax({
...
data: arr,
...
});
try this
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: arr,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});

how to convert $.post form to $.ajax form?

I am noob at using jquery and ajax. I need to change the form from $.post to $.ajax .
var disqus_config = function() {
this.callbacks.onNewComment = [function(comment) {
$.post("sendnotification", { comment: comment.id, post: $post->id,author:$author->id}, function(result){
alert(result);
});
}];
};
I know I need to end something like here but I am stuck how to use post datas(comment,post,author) inside this function
$.ajax({
url: 'sendnotification',
type: 'POST',
data: 'query=' + query ,
dataType: 'JSON',
async: true,
success: function(data){
process(data)
}
Thanks
Just use the same object literal you did for $.post, eg (gotta assume that's some PHP or something in there)
$.ajax({
url: 'sendnotification',
type: 'POST',
data: { comment: comment.id, post: {$post->id}, author: {$author->id} },
dataType: 'json',
async: true,
success: function(data){
process(data)
}
});
I believe dataType: 'JSON' should be changed to dataType: 'json'
Also, use the same data array as you used in your $.post variant.
$.ajax({
url: 'sendnotification',
type: 'POST',
data: { comment: comment.id, post: $post->id,author:$author->id } ,
dataType: 'json',
async: true,
success: function(data){
process(data)
}
});

Jquery - Send variables to a controller Action via GET in AJAX

All,
I want to send a variable "itemId" via GET to a controller action through AJAX. In the Controller Action, I should be able to retrieve the value using $_GET["itemId"];
Can I send the querystring with "data" tag instead of appending it to the "url"?
I have the following code:
$.ajax({
type: 'GET',
url: "/controller/controlleraction",
data: itemId,
cache: false,
dataType: "html",
success: function(html_input)
{
alert(html_input);
}
});
How can I do this?
data: {itemId: itemId},
$.ajax({
type: 'GET',
url: "/controller/controlleraction",
data: ({itemId: itemId}),<------change it to this
cache: false,
dataType: "html",
success: function(html_input)
{
alert(html_input);
}
});
Make itemId a JavaScript object before making the AJAX request. For example:
var itemId = {'itemId': 1000};
data: {itemId: "you info"},
or
data: "itemId=you info",

Categories