Sending string variable from PHP back to ajax with array variable...? - php

I would like to save a message in PHP variable and send it back with my other array variable that is already coming back. For instance, I have some error checking that takes place inside the PHP code and would like a string variable with the specific message sent back for use in my javascript.
Here is the PHP:
<?php
include('config-searchres.php');
$term = $_POST['resid'];
$sql = mysql_query("SELECT * FROM ap_form_8 WHERE id = '$term'"); //select first name (element_1_1) from form #8
if ($row = mysql_fetch_array($sql)){ //if reservation number exists
if ($row['element_11'] != 'Cancelled'){ //if reservation has not already been cancelled
if (strtotime($row['element_3']) >= strtotime(date("Y-m-d"))){ //if reservation has not already passed date
echo json_encode($row);
}
else //Reservation already passed (old reservation)
{
echo 'passed';
}
}
else //Reservation already cancelled
{
echo 'cancelled';
}
}
else //Reservation not found
{
echo 'not found';
}
mysql_close();
?>
As you can see, there are 3 different messages, "passed", "cancelled", and "not found"... if one of these conditions exists, I would like to send this string back to my javascript so I can display it in a DIV. However, I also want to send the $row data with it.
My javascript:
<script type="text/javascript">
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(function(event){
event.preventDefault(); //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
$('#reservation-id').val(resCheck); //add read ID back into text box
var jsonData = $.parseJSON(data); //parse returned JSON data so we can use it like data.name, data.whatever
//****I wanted the line just below this to display the appropriate message sent back from the PHP****
$("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
$('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'], reservation_id:jsonData['id'], reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
$("#res-cancel-message").html('');
},
error: function(){
$("#res-message").html('<a>There was an error with your request</a>');
$("#res-cancel-message").html('');
}
});
});
});
</script>
I marked with asterisks where I populate the DIV with a static message at this time, this is the line where I would populate the message from PHP. Any ideas?

You could add that message as one of your JSON properties and then search for it appropriately.

You can always wait a little with echoing json encoded $row.
Add $row and you message to an array variable, which you json encode and echo out.
Not 100% sure about syntax details/dots
$response_array = array('message' => 'yourmessage', 'row' => $row);
echo json_encode($response_array);

Send both in ajax. LIke
Dont echo anything in the body of your if else, just store the message in variable, say, $message = 'passed', now do this at the end of your php request page:
echo json_encode(array('message_js'=>$message, 'row_js' => $row));
This sends json array as responce so u can send as much variables in it as much u like. Just put them in an array() and convert them into json using json_encode()
to convert into json and pass as response. When recieved in success function of your ajax, just decode the two json variables : message_js and row_js.
You can use parsejson of jquery to get your variables then

Just pass the appropriate message from the server .let us suppose your message is in message variable:
$("#res-message").html('' + data.message +'Reservation ID Located, Information is displayed below');

By the time you convert your row data into the $row, it is an array. You can, if you dare, simply add your message to that array before you json_encode it.
$row["message"] = ...

You can do it this way:
$result = array();
if ($row = mysql_fetch_array($sql)){ //if reservation number exists
if ($row['element_11'] != 'Cancelled'){ //if reservation has not already been cancelled
if (strtotime($row['element_3']) >= strtotime(date("Y-m-d"))){ //if reservation has not already passed date
$result = array('status' => 'OK', 'data' => $row);
}
else //Reservation already passed (old reservation)
{
$result = array('status' => 'passed', 'data' => $row);
}
}
else //Reservation already cancelled
{
$result = array('status' => 'cancelled', 'data' => $row);
}
}
else //Reservation not found
{
$result = array('status' => 'not found', 'data' => null);
}
echo json_encode($result);

Related

retrieve data in different format

Two forms submissions on the same page. two form and fields with diffent ID and names.
One of the two form is working well but I have problem with the second one
I need to get my errors messages normally if wrong entry and if every thing is ok I need array data cause I want to code a message on form step two
My php code :
//To get errors messages normally
if(!empty($errors2)) {
$data != "noPassed";
echo display_errors2($errors2);
}
else {
//To retrieve data I need to code my message in step 2
$data2 = array();
$data2['client_id'] = $client_id;
$data2['client_civilite'] = $client_civilite;
$data2['client_name'] = $client_name;
$data2['res2'] = "passed";
header('Content-Type: application/json');
echo json_encode($data2);
}
Script :
jQuery.ajax({
url : '/myfolder/parsers/check.php',
method : 'POST',
type : 'POST',
data : data,
success : function(data){
//I presume errors in followed condition
if (data != 'passed') {
jQuery('.messages_erreurs').html(data);
}
if(data2.res2 == 'passed') {
$(".frm").hide("fast");
$("#step2").show("slow");
$(".open1").css("display","none");
$(".open2").css("display","inline-block");
// accès à data.client_civilite, data.client_id, pour message d'identification .
$('#clt_id').val(data2.client_id);
$("#check_ok").html(data2.client_civilite+" "+data2.client_nom+" "+': identification réussie.');
}
function to get error messages :
function display_errors2($errors2) {
$display2 = '<ul class="bg-danger">';
foreach ($errors2 as $error2){
$display2 .= '<li class="text-danger">'.$error2.'</li>';
}
$display2 .= '</ul>';
return $display2;
}
First you should decide what to send back from the php script so that you can easily parse it on the javascript side: Text, html or json.
When the request is successful, you send back json but I don't see that header when there is an error so I suspect you are sending back regular text in that case.
When you send back json, you need to make sure it is parsed before you can use it. You can do that by setting the dataType property. Then your data variable will be an object (based on the php script...) so you can access the values:
jQuery.ajax({
url : '/myfolder//parsers/check.php',
method : 'POST',
// Set the correct data type
dataType : 'json',
data : data,
success : function(data){
// Access the correct values
if (data.res2 != 'passed') {
// You need to set the errorText property (or similar) in php
jQuery('.messages_erreurs').html(data.errorText);
}
// etc.

Ajax, JQuery & PHP - Passing PHP variable to JQuery

I have a page that allows users to upload multiple files and preview them without refreshing the page using jquery. In php I generate a unique file_id for each filename which I would then like to pass back in to JQuery and use it to load up the preview image etc.
I hope I have explained myself clearly.
Thanks for any pointers!
The PHP code:
// php code to upload file and generate unique file id. then...
if (move_uploaded_file($main_image, $file)) {
echo "success";
echo $file_id; // <--- I WANT TO PASS THIS VARIABLE BACK IN TO JQUERY
} else {
echo "error";
}
The J Query Code:
$(function(){
var btnUpload=$('#upload_main');
var mestatus=$('#mestatus');
var button=$('#button');
var files=$('#main_file');
new AjaxUpload(btnUpload, {
action: 'classified-ads/upload-classified-image.php?filenumber=1',
name: 'file1',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif|'')$/.test(ext))){
// extension is not allowed
mestatus.text('Only JPG, PNG or GIF files are allowed');
return false;
}
mestatus.html('<img src="extras/ajaxuploader/progress_bar.gif" height="30" width="340">');
button.html('Loading...');
$('#upload_main').removeClass('hover').addClass('upload_button_loading');
},
onComplete: function(file, response){
//On completion clear the status
mestatus.text('Photo Uploaded Sucessfully!');
button.html('Change Photo');
$('#upload_main').removeClass('upload_button_loading').addClass('upload_button');
//On completion clear the status
files.html('');
//Add uploaded file to list
if(response==="success"){
var file2 = file.replace(/\s/g, "_");
var file_id= file_id;
$('<div></div>').appendTo('#main_file').css('background-image', "url(/ht/classified-ads/temp_images/prev1_<?php echo $parsed_user;?>_"+file_id+")").addClass('main_success');
$("#image1_temp").val("main1_<?php echo $parsed_user;?>_"+file_id+"");
$("#thumbnail_temp").val("thumbnail_<?php echo $parsed_user;?>_"+file_id+"");
} else{
$('<li></li>').appendTo('#main_file').text(file).addClass('error');
}
}
});
});
In your PHP:
$response = array('result' => 'success', 'file_id' => $file_id);
echo json_encode($response);
In your jQuery:
var obj = $.parseJSON(response);
You would then check whether the response was a success with if (obj.result == 'success') and you'd get your file_id with obj.file_id
The simplest way is to do this allowing for MULTIPLE values to be returned:
// Make a variable to hold data to send back and keep track of your separator
$data = '';
$separator = 1;
// Put this in a loop, your loop will depend on how many file uploads you have
// I did not do the loop for you
if (move_uploaded_file($main_image, $file)) {
// echo "success"; Take this out
if ($separater==1){
$data .= $file_id;
} else {
$data .= ','.$file_id;
}
$separater++;
}
// Now outside the loop echo the results back
echo $data;
With this info echoed back you can manipulate it with Javascript (Jquery). Just use something like spli(','); which gives you an array of the file names you needed.
If you only want one value to come back, meaning you only have one file id to send back foregt everything about the loop and the PHP would be this:
if (move_uploaded_file($main_image, $file)) {
// echo "success"; Take this out
$data = $file_id;
// Now echo the results back
// Its been a while since I've done this but there may be times its ok to use return
echo $data;
} else {
// Handel error here
echo "error";
}
Now based off your code this echoed information should be picked up and processed here:
onComplete: function(file, response){ ... }
Instead of looking for "Success" you need to change your code to look for a file id or something like error instead (which is easier) like so:
if(response!=="error"){
// Now you can use your variable "response" here since it contains the file id
} else {
// Handle the error
}
The reason I gave you a long explanation about getting multiple values back is because that is more common as you start making more advanced forms and it wouldn't hurt to use now. This way you can allow multiple file uploads for example. What I do for example when using AJAX is echo back something like this:
1::value,value,value
Now I just split that into arrays first by :: and then by , this line for example says No Error Happened (1 which as we know is also TRUE) and here is your data: value,value,value which you can now use for things in your Jquery or just print to the document.
You should look at the Jquery AJAX page for in depth examples and explanations, it explains the trouble you ran into getting results back. Look at .done .success .complete especially.

Why the static message is not coming from ajax file if no data found in mysql database?

I have a very strange problem and couldn't figure it out. I am working with AJAX/PHP and fetching the data from mysql database on user interaction by ajax call. Everything is working very fine and no problem at all. But only one issue which is persisting is when the data is not found in mysql database, then a user-friendly message is not returned from the server ajax file - the one part works and other doesn't. Here is my code -
This is my first file where the form reside (full code is not there; only js code) -
<script type="text/javascript">
$(document).ready(function(){
$("#selcustomer").change(function(){
var customers_id = $(this).val();
if(customers_id > 0)
{
$.ajax({
beforeSend: startRequest,
url: "ajax/ajax.php",
cache: false,
data: "customers_id="+customers_id,
type: "POST",
dataType: "json",
success: function(data){
if(data != "No result found.")
{
$("#img_preloader").hide();
$("#error").html('');
// $("#txtfname").val(data.fname);
// $("#txtlname").val(data.lname);
for(var key in data)
{
document.getElementById("txt"+key).value = data[key];
}
}
else
{
$("#img_preloader").hide();
$("#error").html(data);
$("input").each(function(){
$(this).val('');
});
}
}
});
}
else
{
$("#error").html('');
$("input").each(function(){
$(this).val('');
});
}
});
});
function startRequest()
{
$("#img_preloader").show();
}
</script>
And this is my server-side ajax file (php file) which interacts with database -
<?php
include("../includes/db-config.php");
if(isset($_POST["customers_id"]))
{
$customers_id = $_POST["customers_id"];
$query = "SELECT * FROM `tb_customers` WHERE `customers_id` = '$customers_id'";
$rs = mysql_query($query);
if(mysql_num_rows($rs) > 0)
{
$row = mysql_fetch_array($rs);
$customers_first_name = $row['customers_first_name'];
$customers_last_name = $row['customers_last_name'];
$customers_email_id = $row['customers_email_id'];
$customers_phone_no = $row['customers_phone_no'];
$customers_address_line_1 = $row['customers_address_line_1'];
$customers_address_line_2 = $row['customers_address_line_2'];
$customers_country = $row['customers_country'];
$data = array('fname' => $customers_first_name, 'lname' => $customers_last_name, 'emailid' => $customers_email_id, 'phoneno' => $customers_phone_no, 'addressline1' => $customers_address_line_1, 'addressline2' => $customers_address_line_2, 'country' => $customers_country);
echo json_encode($data);
}
else
{
echo "No result found.";
}
}
?>
The if part is working fine but when no data is found in database the else part is not sending the data back to jQuery code. I checked in browser console and saw the else part is returning the response but the jquery code in success: part of $.ajax is not running - neither within if, nor in else and also not outside of if/else. I mean to say that a simple alert is not fired with data under success when no data is found in mysql database. But when i remove all the data in ajax/php file and say simply write 123 then alert comes with 123 but not when the actual code is there. Can you plz tell me what is the issue behind this strange problem?
Your datatype is set to JSON in your AJAX call, so the return value must be a valid JSON.
When you are encountering the else condition, you are returning something that is not JSON.
Try this -
else
{
echo json_encode("No result found.");
}
Or something more flexible-
else{
echo json_encode(Array("err"=>"No result found."));
}
EDIT-
...But when i remove all the data in ajax/php file and say simply write
123 then alert comes with 123...
That is because a 123 (number) is valid JSON. Instead of 123, try writing No result and an error would be thrown, because No result (a string) needs quotes(which is taken care when you use json_encode).

Conditional if statement after AJAX post using response, is this ok?

A form i'm using with a single input uses AJAX to post to the server. I plan to take the input's value which is a string and check if the string already exists in the database. I'll us in_array() and if the string doesn't exist insert it to the database and echo 1 or else 0 if it's a duplicate, sending back 1 or 0 as a result.
In my AJAX i'm using this simple function on success, if the result returns 1 i'll use jQuery to display a success message, or else i'll display an error and exit. Is this a good method to validate server side and not have the form submit by returning 1 or 0 and exit(); for duplicates?
success: function(result)
{
if(result == 1)
{ string was inserted to db }
else
{
duplicate exists
exit();
}
Thanks
I would have personally made it so in the php, I return a json encoded identity array with some of the information about the response. I usually include more information than needed, for debugging purposes and possible future changes.
if($results >= 1){
$duplicate_exists = 'true';
}elseif($results < 1){
$duplicate_exists = 'false';
};
$result = array(
'exists' => $duplicate_exists ,
'status' => $status,
'time' => time()
// etc
);
echo json_encode($result)
Then to decode the json into an object in javascript:
success: function(result){
result = jQuery.parseJSON(result)
// you can also use eval(result) , but it's much slower.
if(result.exists == 'false'){
// string was inserted to db
}else{
// duplicate exists
exit();
}
You can use the below code using AJAX and JS to post and retrieve the result.
$.ajax({
url: 'https://api.github.com/gists',
type: 'POST',
dataType: 'json',
data: JSON.stringify(data)
})
.success( function(e) {
res = jQuery.parseJSON(e);
if(res.exists == 'false'){
// string was inserted to db
}
else if(res.exists == 'true'){
// duplicate exists
exit();
}
})
.error( function(e) {
//there was error
});

JQuery Do something when data returned from .post

I have a site that is sending off using the .post function in JQuery to run a php script. This script adds some data to a database but if the data already exists in the database it doesn't add the data. Depending on whether the data is added or not I want the javascript to do different things. I don't know how to get the php to return a value that says "data entered" or "data not entered" so the javascript can use that value to decided upon it next action.
Here is the javascript, I only want the append to happen if the php returns that the data was entered into the database.
$('#addpios').click(function() {
var scopesheetidvalue = $("#scopesheetid").val();
var piovalue = $("#pioselected").val();
$.post("addpio.php", { scopesheetid: scopesheetidvalue, pionumber: piovalue },function(data){
$('#pioslist').append("<li><input class='removepio' type='submit' value='"+piovalue+"' /><span class='listitem'>PIO "+piovalue+"</span></li>");}
);
});
Here is the PHP
$scopesheetid = $_POST['scopesheetid'];
$pionumber = $_POST['pionumber'];
$alreadyexisitssql = "SELECT * FROM [ScopesheetPIO] WHERE [ScopesheetID]='$scopesheetid' AND [PIONumber]='$pionumber'";
$alreadyexisits=odbc_exec($connection,$alreadyexisitssql);
if(odbc_fetch_row($alreadyexisits)){
//retrun a value that says the data already exists
}
else{
$addpiosql = "INSERT INTO [ScopesheetPIO] ([ScopesheetID], [PIONumber]) VALUES ('$scopesheetid', '$pionumber')";
$addpioresult=odbc_exec($connection,$addpiosql);
//retrun a vlaue that the data was added
}
What I really want is a way to pass a value from the PHP script back into the Jquery
I would modify your jQuery to the following:
$.post('addpio.php', { ... }, function(data) {
if (data.result) {
$('#pioslist').append(...);
}
}, 'json');
In your PHP file, use this when the data is inserted:
echo json_encode(array(
'result' => TRUE
));
Use this when the data already exists:
echo json_encode(array(
'result' => FALSE
));
Build an array in PHP and output it as JSON. Then inspect the returned JSON in your script.
if(odbc_fetch_row($alreadyexists)){
// Return a value that says the data already exists
$result = array(
"error" => "Data already exists"
);
} else {
// Database stuff goes here...
// Return a value that the data was added
$result = array(
"success" => 1
);
}
echo json_encode($result);
JavaScript $.post callback:
function(data) {
if(data.success) {
// Append element to HTML
} else {
// An error occurred, inform the user
// Don't actually use alert(), this is just for demonstrating purposes
alert(data.error);
}
}
Later on, you can then create more complex responses with extra data by simply adding them to the $result array and reading them from data in your JavaScript.
Write anything in your PHP that you'll test in your callback function :
PHP
if(odbc_fetch_row($alreadyexisits)){
echo "ko";
}
else{
$addpiosql = "INSERT INTO [ScopesheetPIO] ([ScopesheetID], [PIONumber]) VALUES ('$scopesheetid', '$pionumber')";
$addpioresult=odbc_exec($connection,$addpiosql);
echo "ok";
}
JS
$.post("addpio.php", { scopesheetid: scopesheetidvalue, pionumber: piovalue },function(data){
if( data == 'ok' ) {
$('#pioslist').append("<li><input class='removepio' type='submit' value='"+piovalue+"' /><span class='listitem'>PIO "+piovalue+"</span></li>");
}
});
You can easily pass data from a script to jQuery. IMO I think its best to use JSON as its much more neater.
PHP (for example):
$arrayOfData=array("val1"=>"value","val2"=>"value");
//encode it
$arrayOfData=json_encode($arrayOfData);
//print it on screen
echo $arrayOfData;
And then get it in jQuery using the .getJSON.
$.getJSON("url_of_php_fle",function(myData){
//now use myData as the array:
alert(myData.val1);//which will give you "value" as what you set in PHP
}):
It really is that easy.

Categories