<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/
Related
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"]);
I've just started learning jQuery and PHP, and I encountered a problem when I try to use Ajax. Either the $.ajax() function won't fire, or PHP won't return anything, I cannot tell. I must have forgotten something really stupid, I guess...
Here's the code. There's no reply, no alert, nothing.
js:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url: "get_profile.php",
type: "GET",
data: {},
done: function(response) {
alert("response");
}
});
});
</script>
PHP:
<?php echo "Something"; ?>
Thanks in advance.
$.ajax({
url: "get_profile.php",
type: "GET",
data: {},
done: function(response) {
alert("response");
}
});
supposed to be
$.ajax({
url: "get_profile.php",
type: "GET",
data: {},
}).done(function(response) {
alert("response");
});
success , error methods are generally declared in the place where you have written done which are now deprecated
You have your done in the wrong place.
Try this instead:
$.ajax({
url: "get_profile.php",
type: "GET",
data: {}
})
.done(function(response) {
alert("response");
});
You can have alternative option for check is there any error in your ajax call. and you can also do some stuff before getting the response of your ajax call like loading image shows to end users until the response result. for this you can use following code:
$.ajax({
url: "get_profile.php",
type: "GET",
data: {},
beforeSend:function(){
//do something like loading image
},
success:function(response){
alert(response);
},
error:function(e){
alert("something wrong"+e);
}
})
First, I'm using the codeigniter framework and I'm a beginner in JS and AJAX, so please bear with me.
I read this question, so I tried to follow the answers.
This is the script (UPDATED):
$(function() {
$( "#datepicker").datepicker().click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
return false;
});
});
And this is my datepicker HTML code:
<input type="text" id="datepicker" name="datepicker"
value="<?php echo isset($umat['tanggal_lahir'])?$umat['tanggal_lahir']:""?>"/>
My questions are (UPDATED):
Is the URL I provided in AJAX above correct?
How should I pass the data from AJAX to PHP (url: "<?php echo base_url(); ?>backend/umat/add")?
Thanks for your help :D
What you have missed here:
your click event is outside of the doc ready handler, that should be inside doc ready so that when page gets ready the element should be available to click.
You have missed a closing }); tag of the click event.(does not matter though)
so try this:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: {frmData : $('#form_daftar').serialize()}, // <----send this way
success: function(data) {
console.log(data.date);
// here data is the returned data from the specified url and make sure
// that url is generating a proper json structrue.
// suppose there is a key named date which holds the submitted date so
// data.date will get you the date.
}
});
}); //<----you missed this closing of click function.
}); //<----------put everything before this closing of doc ready handler.
Although you can chain it too like this:
$(function(){
$( "#datepicker").datepicker().click(function() {
//......ajax function in click here
});
});
See a demo here
Another approach would be to use the datepicker inbuilt methods to trigger ajax request like
$('#datepicker').datepick({
dateFormat:"yyyy-mm-dd",
onSelect:function(){
$.ajax({
type: 'POST',
url: "<?php echo site_url('backend/umat/add'); ?>",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
}
});
Check the manual or inbuild functions and callbacks with your datepicker js.
try it:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").change(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
});
php get data form ajax:
<?php
$date = $_POST["datepicker"];
?>
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);
}
});
Ok so I know long hand ajax but trying to use the jQuery short cut. I have two documents
form.php
submit.php
In my "form" page I am calling the "submit" page to process the insert. I am currently using the jquery ajax:
<script type="text/javascript">
jQuery('form').submit(function() {
string = jQuery("form").serializeArray();
jQuery.ajax({
type: "POST",
url: "submit.php",
data: string,
dataType: "json",
})
return false;
});
</script>
When I view firebug it is processing the ajax fine. I am getting 200 and post parameters are set. What I am trying to do is have the ajax return the submit.php file. I know it has something to do with the "success" function but I don't know how to add this. I tried a few things like:
<script type="text/javascript">
jQuery('form').submit(function() {
string = jQuery("form").serializeArray();
jQuery.ajax({
type: "POST",
url: "submit.php",
data: string,
dataType: "json",
success: function(html){
alert(html);
}
})
return false;
});
</script>
and
<script type="text/javascript">
jQuery('form').submit(function() {
string = jQuery("form").serializeArray();
jQuery.ajax({
type: "POST",
url: "submit.php",
data: string,
dataType: "json",
success: function(html){
$('.result').html(data);
}
})
return false;
});
</script>
but neither of these are working. Again I am simply trying to send the ajax request and then return the contents of the submit.php page. Not only does the submit.php page hold the script to process the php/ajax insert but it also display success statements like "insert was successful" so that is why I need to not only run the script in the page but also return the contents of that page. Thank you for any help.
Chagne the dataType:'json' to dataType:'html' for the callback that you wish to display the contents of submit.php.
You were close in your second attempt, but you made a typo. Try:
success: function (data) {
$('.result').html(data);
}
Also, unless your server is returning JSON, you probably want to change the dataType:
dataType: "html"