Choosing Error Message on AJAX Call - php

I'm new to using AJAX (but decently experienced in jQuery and PHP) and am wondering if I can have several different error messages on one AJAX call depending on what occurs.
Here is my AJAX function. I'm basically checking the username and e-mail that are used on an HTML form on the page. I'm sending those values to be checked in the database, and if they exists, I need to display an appropriate error message. I need two different messages though. One to say 'That username already exists. Please try again.' and one for e-mail.:
var username = $('input[name="username"]').val();
var email = $('input[type="email"]').val();
var myData =
'username='+ username +
'&email='+ email;
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'signup_ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
$('#register_form').submit();
},
error:function (xhr, ajaxOptions, thrownError){
alert('There was an error.');
}
});
I'm assuming these error messages would come on a 'successful' AJAX call because it's not that the call wouldn't connect to the database, it just wouldn't produce results. I'm figuring there is a way to send data back to the form page from the AJAX PHP page? I was thinking of setting an error message variable to a certain value on the PHP page and then trying to send it back to the Javascript page to be displayed. Is that possible to do? I know I can do these through two separate AJAX calls but I'm just trying to see if it's possible to streamline it into one function. Thanks!

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

Execute other server script on the page which called through ajax call

I have a situation;
I'm calling PHP page through AJAX which require to execute a script on other server which has the email server rights. To be more specific on PHP page after Entering data in Database I have to access the Email server with certain parameters in Query String.
On index.php page i have submit button which enters the data in database through AJAX call and then have to send an email to the user for information.
but for email i need to execute PHP script on other server which have Email server access.
CLIENT SIDE
$.ajax({
url:'vpms/server/updating.php',
type:'POST',
data:formvalues,
success: function(data) {
closelightbox('black_overlay','vendorfeedback',ref-1,'CLOSE');
}
});
IN updating.php
enter code here
if($_POST['Type']=='SUBMITRATING')
{
$sql->Query("INSERT INTO vpms_procurement(`prno`,`vn`,`category`,`paymentterms`,`c1`,`delivery`,`c2`,`communication`,`c3`,`dated`,emaildate ) VALUES('$_POST[PRNO]','$_POST[$vendor]','$_POST[$category]','$_POST[$payment]','$_POST[$payment_txt]','$_POST[$delivery]','$_POST[$delivery_txt]','$_POST[$response]','$_POST[$response_txt]',NOW(),'$_POST[$date]')");
}
$enc=Autoloader::encrypt(serialize($array));
// Sending request to other server for email
header("Location: 10.89.6.2/managerConfirmation.php?token=$enc"); // This is not possible through ajax call
//OR
exec("10.89.6.2/managerConfirmation.php?token=$enc")
}
Options which I may think of.
Using exec("PHP script?q=value");
Or on success of Ajax call make another call through JSONP to access remoteserver.
But I don't know how practical these options are, because I'm also using encrypted data in query string.
your code is vulnerable to sql injection you need to escape all get and post
send use ajax call on successful return of first ajax call
Use 2nd Ajax call on 1st successful ajax response.
$.ajax({
url:'vpms/server/updating.php',
type:'POST',
data:formvalues,
success: function(return_data) {
//Make 2nd ajax call here and run the remote script
enc = return_data ;
$.ajax({
url:'10.89.6.2/managerConfirmation.php?token='+enc,
type:'POST',
data:anything,
success: function(data) {
closelightbox('black_overlay','vendorfeedback',ref-1,'CLOSE');
}
});
}
});
Eventually i had to go with option of another ajax call , but i wanted to share a strange case.
It might help someone.
I used Ajax call which had no Callback and each request also had the failure message
"XMLHttpRequest cannot load 'Remote server address' Origin http://mystuff.local is not allowed by Access-Control-Allow-Origin"
but strangely each request also Succeeded with the delivery of email..

PHP reload page when adding forms (maybe needs ajax)

Sorry for maybe incorrect title for the topic, but this is the best that I came up with.
So, I'm building admin panel for a website.
I have a page, and in some part of the page, i'd like to refresh it and load another form.
let's say add a schedule, and somewhere down on the page I'd like to have this form displayed as soon as the link is clicked.
when a user saves it, I'd like that form to disappear and and in stead of that to have a list displaying all of the schedules.
I don't want to use frames - I'm not a supporter of frames. The panel is built using PHP.
Maybe this might be achived with Ajax? If yes -> How? any link to good example or tutorial.
yes this will be solved with ajax.
Here is a code example when the page is supposed to refresh
$('#button').click(function() {
$.ajax({
url: 'path/to/script.php',
type: 'post',
dataType: 'html', // depends on what you want to return, json, xml, html?
// we'll say html for this example
data: formData, // if you are passing data to your php script, needed with a post request
success: function(data, textStatus, jqXHR) {
console.log(data); // the console will tell use if we're returning data
$('#update-menu').html(data); // update the element with the returned data
},
error: function(textStatus, errorThrown, jqXHR) {
console.log(errorThrown); // the console will tell us if there are any problems
}
}); //end ajax
return false; // prevent default button behavior
}); // end click
jQuery Ajax
http://api.jquery.com/jQuery.ajax/
Script explained.
1 - User clicks the button.
2 - Click function initiates an XHR call to the server.
3 - The url is the php script that will process the data we are sending based on the values posted.
4 - The type is a POST request, which needs data to return data.
5 - The dataType in this case will be html.
6 - The data that we are sending to the script will probably be a serialization of the form element that is assigned to the variable formData.
7 - If the XHR returns 200, then log in the console the returned data so we know what we are working with. Then place that data as html inside the selected element (#update-menu).
8 - If there is an error have the console log the error for us.
9 - Return false to prevent default behavior.
10 - All done.

I want to make a availability button on my registration page

Many websites have an "check availability" button. And I want to have this to. But this seems to be only available when using Ajax and Jquery. Is there any way for me to do this using only PHP and Javascript. Because i'm a starting programmer, which does not have the skills to work with Ajax or Jquery.
What I want, I have a username field. I typ in a username, and I want to check if the name is available. If the person clicks on the check availability button, I want a pop-up that says "This username is available" or "This username has already been taken".
If any knows how to do this in just PHP and Javscript, I would be very obliged to know.
Using ajax (and jquery) is easier than it seems. on your client-side you have a request like this:
$.ajax({
url: 'usernameChecker.php',
dataType: 'GET',
data: 'username=' + $("#yourUserNameFieldID").val(),
success: function(result)
{
alert(result);
}
});
Of course you need to include jquery to implement this. jQuery makes it easy to make ajax-calls.
On your serverside you can use something like this:
<?php
if(isset($_GET["username"]))
{
// check username
if(username_is_free)
// of course this needs to be a bit different, but you'll get the idea
{
echo "Username is free!";
}
else echo "Username is taken!";
}
?>
$(document).ready(function(){
// available-button is the ID of the check availability button
//checkAvailability.php is the file which gets the username param and checks if its available
// user is the id of the input text field where the user enter the username
// available-message is the id of a div which displays the availability message. Use this instead of alert
$('#available-button').click(function() {
$.ajax({
type : 'POST',
url : 'checkAvailability.php',
data: {
username : $('#user').val()
},
success : function(data){
$('#available-message').text(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("Some Error occured. Try again")
}
});
return false;
});
});
Use jQuery ajax, that is the best & easy way to do it.
Using Ajax send a request to a php page which will take username as parameter (get or post method, you can specify in ajax call) and then on server side search for uniqueness of username in database & return appropriate response.
Is there any way for me to do this using only PHP and Javascript.
Because i'm a starting programmer, which does not have the skills to
work with Ajax or Jquery.
I think you'll find making an AJAX request in jQuery a lot more simple than writing one in pure javascript.
As jQuery is an extension on Javascript, you can use minimal jQuery to make the request to the server, and then deal with the response using pure javascript.
Look into using jQuery AJAX:
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
Here you would change the success part to something like:
success: function(data){
if (data == 1){
$(".message").html("Available");
}
else {
$(".message").html("Already Taken");
}
}
I would recommend using jQuery for this task.
jQuery (or another Javascript library) will make the task simple to complete compared trying to do it without using one of them.
jQuery docs are good and for there are plenty of online tutorials matching what you want to do.
You will benefit from putting in the time to learn about the jQuery library.

Send data from jQuery to PHP for mailing

I’ve a javascript file I’ve been using as an template for a site I’m working on and in that script there is a simple form validation where it – if no error occur – sends data to an PHP page called contact.php.
But I’m unsure on how I “grab” the data send from the JavaScript in my PHP site? The contact.php works – that is, if I, in my form, direct it directly to contact.php it sends the mail without problem. In that file I send the variables like this: $name = $_POST['formName']; and so on and in the end send it to the mail function.
The code in my JavaScript file where it sends the data and display a “successful” message on the same page is:
$.post("contact.php",
{ formFrom: FromValue, formName: NameValue, formMessage: messageValue },
function(data){
$("#loadingImage").fadeOut("fast", function() {
$("#loadingImage").before('<p>The message has been sucessfully send. Thank you!</p>');
});
}
);
The NameValue, messageValue, FromValue is set in the form validation like this var messageValue = $("#formMessage").val();.
Any help would be very much appreciated.
Sincere
- Mestika
Just use the jQuery AJAX call (this syntax is from jQuery 1.5.X):
$.ajax({
type: 'POST'
url: urlString,
data: {formFrom: FromValue, formName: NameValue, formMessage: messageValue}
}).success(function(data, status, xhr) {
var obj = eval('(' + data + ')');
//response as object
});
To send JSON back to the JavaScript, use this function in your PHP:
http://php.net/manual/en/function.json-encode.php
One other thing: as a rule of thumb, it's poor practice to use variable names like "FromValue." Initial capitalization is supposed to be used for class names, not variables (JavaScript developers borrowed this practice from Java).

Categories