Overview:
I'm using the JQuery Form Plugin to send Form Data to a remote file via AJAX. The File then processes the form data and inserts it into the MySQL Database.
Problem:
The Problem is, however, when I want to run code on a successful add, (usually completed using the "success" option, it never runs. Doing further research I found that I needed to send back "responseText" to make the function under "success" run.
Questions:
1) Is this true?
2) How do I go about sending back responseText?
3) (If number on is that it is not true) How do I get the function under success to run?
A few code Snippets:
JQuery (Using the JQuery Form Plugin):
$("#form1").ajaxForm({url: 'submit.php', type: 'post', resetForm: true, success: function () { $('#new-paste').modal({show: false}) }});
I can provide the contents of the remote file (submit.php) if needed.
Thank you in advance!
Change your success to:
function(response) {
$('#new-paste').modal({show: false});
alert(response); // response is the output from the php script it submitted to.
}
Hope this helps.
Alright, so I found the solution.
The Script had to be included on the page itself, not in a remote .js file.
so:
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
Should be included in the head.
Related
I am developing a web app using HTML, PHP and JavaScript. I found a way to call PHP methods that run database operations from the client-side (HTML and JS) using AJAX, here's an example:
if (confirm('Sure you want to do that?')) {
$.ajax({
url: "myScripts.php",
type: "POST",
data: {
paramForOperation: myParam,
option: "doAction1"
},
cache: false,
success: function(response) {
//Here I reload or load another page after server is done
window.open("myPage.php", "_self");
}
});
}
So here I call the php file with the script that does an INSERT/ DELETE / WHATEVER on the database. It works fine, but what if I couldn't insert because the index already exists or any other reason? What if some type of data is wrong and I can't insert it? I know I can validate that on the server side using PHP, but how do I return a message saying "Operation complete" or "You should use numbers on X field"?
I thought of something like alert(response); but what will it return? An echo($msg); from my PHP functions? Is there a way to send the result message on that response thing in AJAX?
Thank you for your help.
Any output of the PHP script will be received in response. Remember, the PHP script runs on the server and just generates output. The PHP code itself never reaches the client.
So, you can just echo a message, and alert it in Response.
Bringing it up a notch, you can return a small piece of JSON or XML that can be parsed and which can contain an error message and some error code, so you script can also respond to that, and maybe change its behaviour (if the insert succeeded, add the new data to the page, for instance).
And of course, instead of returning always code 200 (meaning OKAY) from PHP, you could consider returning other HTTP status codes, so the code already indicates whether something went wrong or not. Depending on the status code, jQuery will execute either the success or the error handler, so it's easy to make different handlers for different situation.
Let your server respond with appropriate HTTP Status Codes and meaningful error messages. Use the error function of the ajax call.
$.ajax({
url: "myScripts.php",
type: "POST",
data: {},
success: function(response) {
/* no error occured, do stuff... */
}
error: function(jqXHR, textStatus, errorThrown) {
/* handle the error, add custom error messages to any DOM objects, ... */
console.log(textStatus, errorThrown);
}
Some docs: $.ajax and HTTP Status Codes
I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.
I have a form which sends data to a CRM. If I create a simple HTML form and send the data to the server it will refresh my webpage and show the text:
{"success":false,"error":{"message":"<whatever the error is>"}}
or
{"success":true,"result":"ok"}
After styling the form and integrating animations and validations and stuff everything still works perfectly. Now the data is sent by using http://jquery.malsup.com/form/#getting-started. The server receives it but the user has no idea whether it did or not.
Using this jQuery form plugin or some other plugin you might want me to use(or even code) please help me display text inside a div whether the operation was successful or not, depending on the server's response.
I have only tried to display the response using the examples provided here: http://jquery.malsup.com/form/#ajaxForm but I have failed until now.
Here I've put together a JSfiddle with some form fields and the jQuery form plugin I am using in order to send the data to the server: http://jsfiddle.net/n78p9/1/.
I hope someone will be able to show me what I did wrong or show me another way of doing this.
Thank you!
EDIT #Arun: so it looks like this:
submitHandler: function(form) {
$(form).ajaxSubmit({
target: '.optional',
resetForm: true,
success: function(responseText){
var result = jQuery.parseJSON(responseText);
if(!result.success){
alert(result.error.message)
}
},
error: function(){
alert('Thank you for your message! Our team will contact you in the shortest possible time.')
}
});
}
I am definitely on the right way, but there is a problem: the error alert actually shows when the response is successful. I do not understand why. I have intercepted the POST request through a local proxy and re-sent it through the server and the server sent back this:
{"success":true,"result":"ok"}
But the script considered it an error. That is why I have inserted that text into the error:alert field:D.
What might be the problem?
Try using the callbacks provided by the library
var options = {
target: '#response',
success: showResponse,
clearForm: true,
success: function(responseText){
var result = jQuery.parseJSON(responseText);
if(!result.success){
alert(result.error.message)
}
},
error: function(){
alert('some error')
}
};
$('#contact-form').ajaxForm(options);
I have a toolbar that exists on all my webpages that makes requests to a server side XML file regularly.
Some of the web pages also make requests to the same XML file, but more frequently. Ideally I would like to, where possible, combine this easily into a single request. Where the toolbar uses the same request that the page made (as the page refresh rate is greater than that of the toolbar)
Is there any way to tell if any jQuery AJAX calls have been made to a certain resources and, if so, be notified on success?
Update:
Based on Darin Dimitrov's answer I have tried the following:
$.ajaxSetup({
success: function(){ console.log("woop"); }
});
This never fires, I presume because the success handler is being overwritten when I make my other AJAX calls.
You could use the $.ajaxSetup() to subscribe for the common events.
Subscribe to all ajax events at the document level;
$(document).bind("ajaxSend", function(){
alert('ajax fired');
});
In your AJAX add response callback, something like this:
$.ajax({
type: "POST",
url: "mypage.php",
data: "name=John&location=Boston",
success: function(data){
alert(data);
}
});
and on your php page where you process AJAX request add some echo statement:
echo "POSTed OK!";
If you post is a success you'll get an alert confirmation.
You can also get a confirmation if it failes but modifying the code slightly:
success: function(result) {
if (result==1) {
alert('Success');
} else {
alert('Failed');
}
}
Good luck!
I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).