Javascript function to change input fields - javascript

I'm trying to check if a user exists in my database and then change the values of my input fields to match that user's information. I have the following code but it doesn't seem to work.
<button onclick="checkAvailability()">Check Availability</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function checkAvailability()
{
$(function()
{
$.ajax(
{
type: 'POST',
url: 'test.php',
data: "name=" + $("#name").val(),
dataType: 'json',
success: function(row)
{
$('#name').val(row[0]);
$('#address1').val(row[1]);
$('#phone1').val(row[2]);
alert('success');
}
});
});
}
</script>
The alert goes off but none of the values are changed. I checked the response using Firebug and the response is a JSON object with the user's information. I'm not sure where the error is. Thank you for any input.

If you have a json object you must use: $("#name").val(row.name);

In case you are getting a json then it might look like this
var json = [{"name": "sample"},{"phone":"sample"},{"address":"sample"}];
When you are doing row[0].
what you get is an object["name":"sample"]
So you must make the following change
success: function(row)
{
$('#name').val(row.name);
$('#address1').val(row.address);
$('#phone1').val(row.phone);
alert('success');
}
Also make sure you have input types with id's name, address1 and phone1

Related

Pull different data strings from JSON via Ajax

My client has a jobs board whose API data I'm pulling via Ajax. I can parse the "jobs" data but cannot seem to pull any thing else. For instance, this works to pull the names of job listings to a select box:
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/jobs/',
type:'GET',
data: 'q=' + "",
dataType: 'json',
success: function( json ) {
$.each(json.jobs, function(i, value) {
$('#myselect').append($('<option>').text(value.title).attr('value', value.title));
});
}
});
But when I change "json.jobs" to anything else like "json.offices" or "json.locations" nothing is pulled. How do I go about accurately targeting these data strings to cull together for a complete careers page? Appreciate any guidance whatsoever thanks.
This is the JSON if you need to take a look:
https://api.greenhouse.io/v1/boards/roivantsciences/jobs/
try pull location.name for all jobs $.each(json.jobs, function(i, value) { $('#myselect').append($('<option>').text(value.location.name).att‌​r('value', value.location.name)); });
Ive done a small test:
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/jobs/',
type:'GET',
data: 'q=' + "",
dataType: 'json',
success: function( json ) {
console.log(json)
}
});
What I got back from console is that your json object only has 'jobs' as the top attribute in it.
You have to go through it like this to get locations:
$.each(json.jobs, function(i, value) {
console.log(value.location);
});
then you have the location object inside this you got the attribute 'name'
so u can get the names with value.location.name

AJAX - submit multiple POST data

I am desperately trying to submit multiple POST variables via AJAX, but just cant get manage to get the formatting right... Problem is that I have both a hardcoded / written action=problem_lookup variable and a dynamic field input as $(this).val and just cant manage to get both into one data string...
this works well:
data: 'problem=' + $(this).val(),
This does not:
data: { action: 'problem_lookup' , problem: $("problem").val() },
data: { action: 'problem_lookup' , problem: $(this).val() },
data: { action: problem_lookup, problem: $(this).val() },
I tried numerous formats from other threads and looked at the official jquery manual, but cant seem to get this figured out. Any help is appreciated.
EDIT:
full script below, tried the solutions posted so far but no success. $("problem") is a <select> field (with Select2 running) hence shouldnt cause me so much frustration, especially since the original approach with data: 'problem=' + $(this).val(), works fine.
$(function () {
$('#problem').change(function () { // on change in field "problem"
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
$.ajax({ // launch AJAX connection
type: 'POST', // via protocol POST
url: 'ajax.php',
//data: 'problem=' + $(this).val(), // send $_POST string
//data:"{'action':'"+action+"','problem':'"+$(this).val()+"'}",
//data:"{'action':'problem_lookup','problem':'"+$(this).val()+"'}",
//data: { action: 'problem_lookup' , problem: $("problem").val() },
//data : data_string,
data: $.param(data),
dataType: 'json', // encode with JSON
success: function (data)
{
// do something
},
});
});
});
An issue is in the
$("problem")
Jquery call.
If.problem is a css class try with
$(".problem")
if problem is a css id try with
$("#problem")
For posting arrays of object you can build data as an object containing arrays, changing a little bit your structure. Something like this
Var obj={};
obj.postData=[];
obj.postData.push(/*your first object here*/);
...
obj.postData.push(/*your n-th object here*/);
$.ajax({
.....
data:obj;
......
});
Try the FormData() FormData.
var data = new FormData();
data.append('action', value);
...
You need to specify your data variable first like this:
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
In AJAX serialize your data using $.param,
data: $.param(data),
Note: Twice check if $("problem").val() is correct. If problem is a class, you need to specify like this $(".problem").val() or if it is ID, $("#problem").val()

(this).parent().find not working for getting response in ajax call

$(".content-short").click(function() {
$(".content-full").empty();
var contentid=$(this).parent().find(".content-full").attr('data-id');
var content=$(this).parent().find(".content-full");
alert(contentid);
var collegename = $(this).attr('data-id');
$.ajax({
type: "post",
url: "contenthome.php",
data: 'collegename=' + collegename,
dataType: "text",
success: function(response) {
$content.html(response);
}
});
});
here the alert displays the specific data-id but
content=$(this).parent().find(".content-full");
this didn't displays data in content-full div with that specific data-id
anything wrong in the code or something else?
the query displays data if i use(."content-full"); instead of
$(this).parent().find(".content-full");
Inside the ajax callback you are using $content, but you declare your variable as content. May that be the problem?
Your question is not clear. What are you trying to achieve?

How to get JSON key and value with ajax

I have json like this :
[{"name":"dhamar","address":"malang"}]
How can I get the key and value from that json with ajax?
I have tried code like this :
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: 'POST',
url: '--url--',
dataType: 'text',
success: function(jsonData) {
$.each(response,function(index,value)
{
$("[name="+index+"]").val(value);
});
}
});
});
</script>
but I get nothing. Anyone please help me, thanks
Try changing the .success() part:
.success: function(jsonData) {
var response = JSON.parse(jsonData);
console.log(response);
}
And remove dataType: 'text',.
You should see the object in your browser console and should be able to iterate with .each() from then on. Please share your results.
I think you want this:
$.each(response,function(key,value){
console.log(key":"+value.name);
console.log(key+":"+value.address);
})
FIDDLE DEMO

Pass Array and String from Javascript to PHP with AJAX

I have the following ajax call.
My addList variable holds a string: list=Sports&list=Cars&list=Outdoor&new_list=123123
I want to grab the addList in my PHP file as
$_POST['list'] is an array with values Sports, Cars, Outdoor
$_POST['new_list'] is a string 123123
But I couldnt convert the POST string into right forms.
I can create arrays/loops in both sides but it didnt feel right.
Whats the convenient way of doing it?
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-list&nonce="+ajax_var.nonce+"&post_list=&post_id="+post_id+"&" + addList,
success: function(count){
alert("done");
}
});
Any help will be appreciated. thanks!
try using followig code.
you just neeed to locate your form if and url to pass values to :
var form = new FormData($('#form_id')[0]);
form.append('view_type','addtemplate');
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});
this will pass all form element automatically.
Working and tested code.
When you pass variable with the ajax method from jQuery, you can pass array like this :
jQuery
var myArray = newArray();
myArray.push("data1");
myString = "data2";
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: {array:myArray, param2:myString},
^name ^value
success: function(count){
alert("done");
}
});
PHP
echo $_POST['array'][0]; // data1
echo $_POST['param2']; // data2
Change your addList variable to this:
list[]=Sports&list[]=Cars&list[]=Outdoor&new_list=123123
PHP will parse the items named list[] into an array, and you'll find the values as $_POST['list'][0],$_POST['list'][1],$_POST['list'][2]

Categories