I am attempting to send a very simple login form from a jQuery Modal form.
$( "#dialog-form" ).dialog({
var url = "../scripts/sign_up.php";
$.ajax({
type: "POST",
url: url,
data: $("#dialog-form").serialize(),
success: function(data){
alert("it works")
}
});
});
This is my first real shot at trying Ajax and I am having issues getting the success method to go through. I have checked that my script is in the right place and that the dialog_form has the right id.
Am I sending this information incorrectly? Is there a good way to troubleshoot Ajax requests?
Right now I am just trying to get the info to go through and, to simply the question, removed other code for the form.
First, I might reccommend adding an error function to your Ajax request as well - it may help with error handling:
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
Second, how are you sending data back from the script to the Ajax request? If you're not echoing back any data from your script, the request is not going to know that the script ran sucessfully.
Therefore, you may want to add the following to your AJAX call:
dataType: "json",
And then return data from your PHP script like so:
$data = array("success"=> true);
echo json_encode($data);
exit;
In full (using your script):
$( "#dialog-form" ).dialog({
var url = "../scripts/sign_up.php";
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: $("#dialog-form").serialize(),
success: function(data) {
if (data.success) {
alert("it works")
}
else {
alert("it failed, but no server error!");
}
}
error: function (jqXHR, textStatus, errorThrown) {
alert("server error");
alert(textStatus);
alert(errorThrown);
}
});
});
Related
I have a pretty standard ajax call for a live update, however, say I call the the ajax, everything is good, but say I want to call it again, this time, I will get 2 calls, and if I try again then I'll have 3, I can verify this by invoking and alert and with the Network DevCon of Chrome, any idea why this is happening?
P.S: I'm using Laravel 5.1
$('button[name=act]').click(function() {
var icon = $(this).closest('div.thumbnail').find('i');
$(document).ajaxStart(function() {
icon.show();
});
$("form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr) {
$(icon).fadeIn(function() {
$(this).removeClass('fa-spinner fa-spin').addClass('fa-check text-success').fadeOut(1000, function() {
$(this).removeClass('fa-check text-success').addClass('fa-spinner fa-spin');
});
});
}/*,
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}*/
});
});
});
The problem is that every time you click on the act button you call $("form").submit(), which adds anothersubmithandler to the form. So if you click on theact` button 3 times, and then click on the form's submit button, it will send 3 AJAX requests.
It's almost always wrong to bind one event handler inside another event handler, you should bind all the event handlers at top level.
var icon;
$(document).ajaxStart(function() {
if (icon) {
icon.show();
}
});
$('button[name=act]').click(function() {
icon = $(this).closest('div.thumbnail').find('i');
});
$("form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr) {
if (icon) {
icon.fadeIn(function() {
$(this).removeClass('fa-spinner fa-spin').addClass('fa-check text-success').fadeOut(1000, function() {
$(this).removeClass('fa-check text-success').addClass('fa-spinner fa-spin');
});
});
}
}/*,
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}*/
});
});
The reason this is happening is because you are rebinding the submit event function every time the button is clicked which results in multiple copies of the function. Just move it out of the click even, and if you want to force a submit on a click, you can call the submit() function with no parameters to fire the event.
Try the following:
$(function(){
$('button[name=act]').click(function(){
var icon = $(this).closest('div.thumbnail').find('i');
$(document).ajaxStart(function()
{
icon.show();
});
$("form").submit(); //This submits the form on click
});
//This binds the function, so it should only be called once.
$("form").submit(function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr)
{
//BLAH
}
});
});
});
I noticed two other things you might want to address. You want to somehow update the icon after it is loaded. You will need to have some other way to find the icon inside of the success function (possibly looking at the data that came back could yield some information that could be useful. Since it is json, it should be easy to update.)
Also, the way you currently have it will bind to all forms on the page. In the event that you have multiple forms on the page, you will probably want to change the selector to use an id.
Hope this helps!
Based in incremental calls and my guessings, I have to say that you're printing this code each time you make the (ajax) call, leading to bind your form element again in each call..
Am I right?
JO.
I am having issues retrieving data from PHP by using Ajax. I am stuck and have been spending lots of time trying to find out where the problem is.
Here is my php code:
<?php //ajax/default_chart_numbers.php
require_once '../core/db_connection.php';
$lotto = new Lotto();
$ultimo_concurso=$lotto->ultimo_concurso('foo');
$ultimos_numeros_m=$lotto->ultimos_numeros('bar');
$R1m=$ultimos_numeros_m[1];
$R2m=$ultimos_numeros_m[2];
$R3m=$ultimos_numeros_m[3];
$R4m=$ultimos_numeros_m[4];
$R5m=$ultimos_numeros_m[5];
$R6m=$ultimos_numeros_m[6];
$R7m=$ultimos_numeros_m[7];
//preparing json
$json=array('y'=>$ultimo_concurso,'n1'=>$R1m,'n2'=>$R2m,'n3'=>$R3m,'n4'=>$R4m,'n5'=>$R5m,'n6'=>$R6m);
print json_encode($json,true);
?>
The output of the PHP file is:
{"y":"2745","n1":"1","n2":"13","n3":"19","n4":"29","n5":"41","n6":"46"}
And here is the jQuery code:
<script>
$(document).ready(function(){
/*Retriving data from PHP file*/
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (response, textS, xhr) {
alert("everything ok :)");
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
},
complete: function(data){
y=data.y;
alert('The id number is '+ y);
}
});
});
</script>
When executing, the value is undefined. I mean, the alert i get is The id number is undefined.
What am i missing?
There's no true in json_encode, there is in json_decode to get an array, but now you're creating a string
change
print json_encode($json,true);
to
echo json_encode($json);
and the complete handler doesn't get the data, it has two arguments, the XHR object and the statuscode, the success handler gets the data
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (data) {
y=data.y;
alert('The id number is '+ y);
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
On PHP side, send the JSON with:
header('Content-Type: application/json');
echo json_encode($json);
Maybe log the incoming data to the console:
inside success: add an console.log(response)
inside complete: add an console.log(data.y)
This is missing:
https://api.jquery.com/jQuery.parseJSON/
try using:
result = $.parseJSON (data);
result.y has your value
I'm using the jQuery AJAX function in order to retrieve data from my mySQL database without having to refresh the page. I have everything in working order, my query's are retrieving the correct data from my database. However, I am struggling to echo out an error message when no data can be retrieved based on the users input. I have a php file that provides the user interface for the user to search from, it also contains the following Scripts in the document head. Here is what I have so far:-
<script type="text/javascript">
$(function(){
$('#users').keyup(function(){
var inpvalue= $('#users').val();
});
});
</script>
<script type="text/javascript">
$(function(){
$('#users').keyup(function(){
var inpval=$('#users').val();
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
$('#output_div').html(data);
}
});
});
});
</script>
Any help would be greatly appreciated, sorry if I haven't explained myself very well.
Thankyou.
Modify your .ajax() call so you can detect error conditions:
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
$('#output_div').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
This is just to get you started: see http://api.jquery.com/jQuery.ajax/ for more details on what you can do with the error handler.
Of course, it's possible that you're getting a good HTTP status from the call, but this defensive programming will make sure.
A tool like Firebug running in your browser can also help you detect bad HTTP status code returns.
In data.php you have to output the error when the data is invalid.
The error setting for $.ajax will only get called if the actual ajax request has a problem like if the server returns a 404. You would have to return an error in your json and check for it like this:
$('#users').keyup(function(){
var inpval=$('#users').val();
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
if(!data.error) {
$('#output_div').html(data);
}
else {
// show error
}
}
});
});
And then you would return your normal json when the data is fine and then something like this for the error:
{"error": "Oh NOES!"}
Hi everyone I'm trying to incorporate jQuery AJAX on my multi-step form so that it updates a certain div to the one on the process.php page but it keeps loading the results on a new page. How can I get it to update the div without refreshing the page?
This is the jQuery code I'm using:
$.ajax({
url: 'process.php',
data: $('form[name="booking"]').serialize(),
dataType: 'html',
type: 'POST',
success: function(data) {
// this is the bit that needs to update the div
$('#last-step').fadeOut(300, function() { $('#result').html(data).fadeIn(300);
},
complete: function (data) {
// your code here
},
error: function (url, XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
This is the code for my multistep form: http://jsfiddle.net/xSkgH/47/.
Many thanks in the advance
I dont see a div called result in your Markup. So probably you need to show your result in the last div you are showing. And you are missing }) also. the below code should work,
$.ajax({
url: 'process.php',
data: $('form[name="booking"]').serialize(),
dataType: 'html',
type: 'POST',
success: function(data) {
// this is the bit that needs to update the div
$('#last-step').fadeOut(300, function() {
$('#last-step').html(data).fadeIn(300);
});
},
complete: function (data) {
// your code here
},
error: function (url, XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
I'm not sure why this is happening, but when my page loads, there's an XHR request immediately for the search results. It's invisible to the user, but it's loading a fairly large chunk of json data.
Here's my code:
$.ajax({
type: "POST",
url: "http://localhost:8888/index.php/ajax/get_client",
dataType: "json", data: "{}",
success: function(data) {
$('#search').autocomplete({
source:data,
minLength:2,
delay:0,
appendTo:'header',
selectFirst:true,
select:function(event, ui) {
$("input#search").val(ui.item.value);
$("#search").closest('form').submit();
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
How can I make it so the json data is only requested when the user types in the input#search box?
It looks like you want to load a list autocomplete results and then initialize the autocomplete plugin only if the user starts typing. To do this, bind a keyup function to the search box, if the results have not been loaded, then load the results and initialize the plugin.
$(document).ready(function(){
var searchInput = $("input#search");
function loadData(onSuccess){
$.ajax({
type: "POST",
url: "http://localhost:8888/index.php/ajax/get_client",
dataType: "json", data: "{}",
success: onSuccess,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
function initializeAutocomplete(data){
searchInput.addClass('loaded').autocomplete({
source:data,
minLength:2,
delay:0,
appendTo:'header',
selectFirst:true,
select:function(event, ui) {
searchInput.val(ui.item.value).closest('form').submit();
}
});
}
searchInput.keyup(function(){
if($(this).is(".loaded")) return;
loadData(initializeAutocomplete);
});
});
Wrap your ajax call into a button.click() event or if you want it calling while the user is typing, put it in a textbox.keypress() event.
You need to bind a keyup event listener to your input box.
If you've inserted this code right inside your html page without a event listener, the code will execute right after your page loads.
This should probably work: http://jsfiddle.net/XNbrX/
I haven't tested it.
I don't know if I understand you, but I think that you want to run this code on every key press (really key up) to load results on every change of search box value.
If I'm right, put your code into function which is triggered on 'onkeyup' event.
$('input#search-box').keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost:8888/index.php/ajax/get_client",
dataType: "json", data: "{}",
success: function(data) {
$('#search').autocomplete({
source:data,
minLength:2,
delay:0,
appendTo:'header',
selectFirst:true,
select:function(event, ui) {
$("input#search").val(ui.item.value);
$("#search").closest('form').submit();
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});