I would like to send a GET request with only one parameter from an input form via AJAX, using jQuery.ajax().
To simplify things, instead of
data: $("#the_form").serialize()
I tried to explicitly pass the value of the input:
function lookupSearch(val){
$.ajax({
type: "get",
url: "/search",
data: {
tx_search_pi1['sword']: val
},
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
Now this breaks because of the brackets and quotes in
tx_search_pi1[sword]: val
(which is required by the recipient of the get request)
How do I escape the brackets (and maybe also single quotes inside= correctly?
I've tried-and-errored many combinations, eg. with
tx_search_pi1%5Bsword%5D
encodeURIComponent("tx_kesearch_pi1[sword]")
etc...
You can try this,
data: $("#the_form").serialize()+'&sword='val,
Full Code,
function lookupSearch(val){
$.ajax({
type: "get",
url: "/search",
data: $("#the_form").serialize()+'&sword='val,
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
And if you want to pass sword value then use,
data: {'sword':val}, // get using sword key
As per #Urs Comment the code should be,
// let it is initialised before,
// and it is an object like {}, tx_search_pi1 = {key:"1",...};
function lookupSearch(val){
tx_search_pi1['sword'] = val;
$.ajax({
type: "get",
url: "/search",
data: tx_search_pi1,
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
try putting tx_search_pi1['sword'] this in a variable and pass it.
Like
var temp = tx_search_pi1['sword'];
And pass temp
Related
$("#nonjstest").click(function() {
$.ajax({
url:"https://petstore.swagger.io/v2/pet/findByStatus?status=sold",
type: "GET",
contentType:"application/json",
success: function(data){
alert(data[0].id)
}
})
})
Here, I am passing the required parameters directly in the URL status=sold.
I want to pass them via a variable instead, but it's not working. I've tried the following:
var requiredata = ["status=sold"]
$("#nonjstest").click(function() {
$.ajax({
url:"https://petstore.swagger.io/v2/pet/findByStatus",
type: "GET",
data: requiredata,
contentType:"application/json",
success: function(data){
alert(data[0].id)
}
})
})
The request itself is successful, but nothing is returned, meaning, the parameters are not passed correctly. What is the problem with the way I'm passing the Array string?
I've tried stringifying the data, but it didn't work either.
Why is it not working? How do I pass the array string data with a variable?
Try sending the params as an object instead of as an array:
var requiredata = {
status: 'sold'
};
$("#nonjstest").click(function() {
$.ajax({
url:"https://petstore.swagger.io/v2/pet/findByStatus",
type: "GET",
data: requiredata,
contentType:"application/json",
success: function(data){
alert(data[0].id)
}
})
});
Another option would be to pass the params as a string but it's worse because you have to pass it already encoded.
Check the docs for more information.
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: {id:id},
dataType: 'json',
success: function(data) {
console.log(data);
}
});
};
The JSON object returned from the get_data.php script is:
{
id: 5,
username: "Anthony",
status: "accupied"
}
I am able to the length of the data object if I do console.log(data.length). However, I can see the object when I console.log(data) in the success property.
I am not able to access the elements of the data obejct if I do console.log(data.username), doing this displays undefined in the console.
I created a variable, data1, outside the scope of the function getReportedInfo and assigned the data retrieved via the success property to
this variable after I tried to display the constents of data1 outside the function.
Sounds like data is a string not an object. You can convert this to an object by using JSON.parse. Try the following code.
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: {id:id},
dataType: 'json',
success: function(data) {
var dataObject = JSON.parse(data);
console.log(dataObject.username);
}
});
};
Edit
After discussing with OP in comments below, it was determined the object returned data was in a structure like the following, and is already in an object form (not a string)
{
"0": {
id: 5,
username: "Anthony",
status: "accupied"
}
}
Therefor the following code should work.
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: {id:id},
dataType: 'json',
success: function(data) {
console.log(data["0"].username);
}
});
};
If in php your return like this way
<?php
echo json_encode($array);
// or
return json_encode($array);
In JavaScript you can use it as you try to use, now, apparently you are not returning a JSON even though you are indicating it in the request, in this case it uses parse:
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: { id:id },
success: function(data) {
var response = JSON.parse(data);
console.log(response.id); // return 5
}
});
};
So I'm trying to achieve the following, but I can't figure out how to make this work.
$.ajax({
url: "whatever.php",
method: "POST",
data: { myVar: "hello" },
success: function(response) {
console.log('received this response: '+response);
console.log('the value of myVar was: '+data.myVar); // <<<< data.myVar is not accessible from here
console.log('the value of myVar was: '+myVar); // <<<< myVar is not accessible from here
}
});
Is there a way to access the value of myVar in the .success() function?
Can I somehow get to the original data object that was sent in this ajax request, in the .success() function?
Hoping for your solutions.
Thanks!
You can use this to access the whole object. So you can do something like this:
$.ajax({
url: "whatever.php",
method: "POST",
data: { myVar: "hello" },
success: function(response) {
console.log('received this response: '+response);
console.log('the value of myVar was: '+this.data.myVar);
}
});
All of the other answers, except for Piyin's, are unreliable and a bad practice.
AJAX requests are, by their very nature, asynchronous. That means that by the time the response gets back from the server, the variable that they set may have been changed. If you want an example, just make two buttons that both fire the same code, but set myData to a different value, and click them each quickly before the response gets back... now the variable has been changed and you'll get unreliable results.
Piyin's answer is good as well, but sometimes you get different formats of the sent data. It might be a JSON object that's been stringify'd, it might be in GET format with query strings, etc.
The easiest way on the coder (although it does create a bit more overhead in RAM) is to assign a new property of the AJAX object and access it in the callback, like this (using Piyin's example):
var dataToSend = { myVar: "hello" };
$.ajax({
url: "whatever.php",
method: "POST",
data: dataToSend,
sentData: dataToSend, //add this property
success: function(response) {
console.log('received this response: ' + response);
console.log('the value of myVar was: '+ this.sentData.myVar); //access sentData property
}
});
Generally, if you want to be able to reference data more than once, you need to make sure it's in the proper scope. The scope of the json data object you're passing inside .ajax() is the ajax function. If you want to be able to reference the value of data: outside of that, for example the scope in which you're calling .ajax(), the simplest way is just to assign it to a variable. eg
myData = { myVar: "hello" };
$.ajax({
url: "whatever.php",
method: "POST",
data: myData,
success: function(response) {
console.log('received this response: '+response);
$("#response").html(response);
console.log('the value of myVar was: '+myData.myVar); // <<<< data.myVar is not accessible from here
$("#myVar").html(myData.myVar);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="response"></p>
<p id="myVar"></p>
Just store the data you are posting in a variable first.
var data = {myVar: "hello"}
$.ajax({
url: "whatever.php",
method: "POST",
data: data,
success: function(response) {
console.log('received this response: '+response);
console.log('the value of myVar was: '+data.myVar);
}
});
Create a data object so that you can then access in various parts of the request
var postData ={ myVar: "hello" };
$.ajax({
url: "whatever.php",
method: "POST",
data: postData ,
success: function(response) {
console.log('received this response: '+response);
console.log('the value of myVar was: '+postData.myVar);
You can always do something like the following:
var myData = '{ myVar: "hello" }';
$.ajax({
url: "whatever.php",
method: "POST",
data: myData,
success: function(response) {
console.log('the value of myVar was: ' + myData.myVar);
}
});
Or even better
var myData = {
myVar: "hello"
};
$.ajax({
url: "whatever.php",
method: "POST",
data: JSON.stringify(myData),
success: function(response) {
console.log('the value of myVar was: ' + myData.myVar);
}
});
I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});
I have a script that makes two ajax calls - the second being contained within the success handler of the first.
However I need to use the data captured within the first success handler as a further variable to pass in the second ajax call and then use that variable within the php file that is undertaking the server side processing.
This is all very new to me, so I hope this makes some sort of sense. If anyone could assist that would be great.
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function (data) {
alert("success data from processone is " + data);
var lead_id = data;
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processtwo.php?lead_id'+lead_id,
data: $('form').serialize(),
success: function (data2) {
alert("success data from processtwo is " + data2)
}
});
}
});
I think you lose a "=" sign in the code:
url: 'processtwo.php?lead_id='+lead_id,
You're going to want to split these into two separate functions and allow for a parameter to be passed to the second. Not really part of your question, but should make it much easier to read. The second process seems to be missing an equals sign in the url parameter which will cause it to not work
function processOne() {
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function(data) {
//alert("success data from processone is " + data);
//console logs are better to use when debugging data
console.log('SUCCESS DATA', data);
var lead_id = data;
processTwo(lead_id);
}
});
}
function processTwo(lead_id) {
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processtwo.php?lead_id=' + lead_id,
data: $('form').serialize(),
success: function(data2) {
alert("success data from processtwo is " + data2);
}
});
}
If you're still not getting anything make sure the data is directly returning the lead_id. AJAX calls commonly return JSON data, so it very well might be something like data.lead_id or something like that. Alerts aren't useful for showing this so you could use the console log, console.log('SUCCESS DATA', data) to dig into the return data.
Given the reply to my comment, and making the assumption that the data returned from the first AJAX call is a simple string value (if it's not, you can still use the code here to see how you need to do what you need to do). jQuery's serialize() returns a string (see https://api.jquery.com/serialize/) so you can just append to that.
Also, you are missing your = sign when making your URL, so if you are trying to get the lead_id as a GET var, that's why it's not working.
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function (data) {
alert("success data from processone is " + data);
var lead_id = data;
$.ajax({
type: 'POST',
timeout: 500000,
// you are missing the equals sign here, which is why this doesn't work as a GET
url: 'processtwo.php?lead_id'+lead_id,
// here we tack on a lead_id variable to the serialized form and give
// it the value you got back from query 1
data: ($('form').serialize() + "&lead_id=" + lead_id),
success: function (data2) {
alert("success data from processtwo is " + data2)
}
});
}
});