Trouble w/ Form Processing using jQuery + PHP - javascript

I'm having the hardest time getting a simple form to process using jQuery and PHP. I've tried getting the data via $_POST, $_GET, and $_REQUEST but I guess I'm missing a simple line of code or a complete process altogether.
app.js
$(document).ready(function() {
$('#sucMsg').hide();
$('#errMsg').hide();
$('form').on('submit', function(event) {
event.preventDefault();
var form = $(this);
alert(form.serialize());
$.ajax(form.attr('action'), {
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: form.serialize(),
success: function(result) {
form.remove();
$('#sucMsg').append(result);
$('#sucMsg').fadeIn();
console.log(result);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError);
$('#errMsg').append(thrownError);
$('#errMsg').fadeIn();
}
});
});
});
formProcess.php
<?php
if ($_POST) {
echo "Posted something.";
} elseif ($_GET) {
echo "Getted something.";
} else {
echo "Nothing is working...";
}
$tagNumberPost = $_POST['inputTagNumber'];
$pricePost = $_POST['inputPrice'];
$makePost = $_POST['inputMake'];
$tagNumberRequest = $_REQUEST['inputTagNumber'];
$priceRequest = $_REQUEST['inputPrice'];
$makeRequest = $_REQUEST['inputMake'];
if (isset($_REQUEST['inputTagNumber'])) {
echo '$_REQUEST works...\n';
} elseif (isset($_POST['inputTagNumber'])) {
echo '$_POST works...\n';
} elseif (isset($_GET['inputTagNumber'])) {
echo '$_GET works...\n';
} else {
echo "Nothing is working...";
}
echo "<br/>";
echo "Tag number: " . $tagNumber . "<br/>\n";
echo "Make: ".$makePost . "<br/>\n";
echo "Price: " . $pricePost . "<br/>\n";
?>
What I'm expecting to get back is the all the echo's in my formProcess.php to print out in my #sucMsg div.

Why are you setting your contentType: as application/json? You do not need that. Remove it.
contentType: 'application/json', // remove this line
Just leave it to its default as application/x-www-form-urlencoded if your request is POST.
And in your PHP, $tagNumber is undefined.
if (isset(
$_POST['inputTagNumber'],
$_POST['inputTagNumber'],
$_POST['inputMake'],
)) {
$tagNumber = $_POST['inputTagNumber']; // define tagNumber
$pricePost = $_POST['inputPrice'];
$makePost = $_POST['inputMake'];
echo "<br/>";
echo "Tag number: " . $tagNumber . "<br/>\n";
echo "Make: ".$makePost . "<br/>\n";
echo "Price: " . $pricePost . "<br/>\n";
}

Related

PHP Ajax , Not able to pass a PHP value from one page to another using AJAX

I have a php code that post value using ajax to another php page , but the value provided is not reflecting in UI nor in console .
$(document).ready(function() {
$('#CustomerName').click(function() {
customername = $(this).text();
load_data(customername);
// console.log(customername); // works
});
function load_data(Customername) {
// console.log(Customername); // works
$.ajax({
url: "getvalueafterclick.php",
method: "POST",
data: {
Customername: Customername,
EnvironmentType: "BA"
},
success: function(data) {
$('#result').html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("some error occured->" + jqXHR.responseJSON);
}
});
}
});
<?php
// perform actions for each file found
foreach (glob("CustomerConfigFiles/*.json") as $filename) {
echo ' <a href="#" id ="CustomerName" class="mm-active">
<i class="metismenu-icon pe-7s-rocket"></i>'.substr(substr($filename,20), 0, -5).'</a>';
}
?>
So when i give console.log in function and onclick , it returns value but when i try to pass CustomerName , it just returns null .
getvalueafterclick.php
<?php
$pat =$_POST['EnvironmentType'];
$lat =$_POST['Customername'];
echo "<script>console.log('Customer Name: " . $lat . "');</script>";
echo "<script>console.log('ENVIRON: " . $pat . "');</script>";
?>
Here is output i get :
Change id to class for CustomerName , I have added/ changed your code, see if it helps to solve your problem.
$(document).ready(function() {
// changed # to . for class
$('.CustomerName').click(function() {
customername = $(this).text();
load_data(customername);
// console.log(customername); // works
});
function load_data(Customername) {
// console.log(Customername); // works
$.ajax({
url: "getvalueafterclick.php",
method: "POST",
data: {
Customername: Customername,
EnvironmentType: "BA"
},
success: function(data) {
$('#result').html(data);
// console added to check what it is giving
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("some error occured->" + jqXHR.responseJSON);
}
});
}
});
<?php
//your code
// perform actions for each file found
// here in link change id to class for customer name
foreach (glob("CustomerConfigFiles/*.json") as $filename) {
echo ' <a href="#" class="CustomerName" class="mm-active">
<i class="metismenu-icon pe-7s-rocket"></i>'.substr(substr($filename,20), 0, -5).'</a>';
}
// my testing code
$data =["a","b","c","d","e","f","g","h"];
// perform actions for each file found
// here in link change id to class for customer name
foreach ($data as $filename) {
echo ' <a href="#" class="CustomerName" class="mm-active">
<i class="metismenu-icon pe-7s-rocket"></i>'.$filename.'</a>';
}
?>
getvalueafterclick.php
<?php
$pat =$_POST['EnvironmentType'];
$lat =$_POST['Customername'];
echo "Customer Name:" . $lat . "-";
echo "ENVIRON: " . $pat ;
?>

How to insert PHP row record into AJAX url

I possible to insert update.php?id=" . $row["id"] . " into AJAX url?
I'm trying to make async sql row updating via form. I don't have specific id, because id is called on click.
JS
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
$.ajax({
type: "POST",
url: 'update.php?id=" . $row["id"] . "',
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
PHP where update.php call is located
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);
$potnik = $row["potnik"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Spremenjena oblika datuma
$date = date_create($row["ura"]);
$ura_pobiranja = date_format($date,"H:i");
echo "<div class=\"row list divider-gray\">
<div class=\"col-1 fs-09 fw-600\">" . $row["id"] . " </div>
<div class=\"col-3 flex-vcenter-items fw-600 fs-09\">" . $row["naslov"] . " </div>
<div class=\"col-1 flex-vcenter-items fw-600 fs-09\">$ura_pobiranja</div>
";
if ($row["naslov"] !== null) {
echo " <div class=\"col-6 flex-vcenter-items fs-1\">Nastavi uro<form id='form' action='update.php?id=" . $row["id"] . "' method='POST'><input id='id' name='potnik' value='".$row["id"]."' type='hidden' /> <input id='cas' class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input id='submit' type='submit' value='Posodobi'> <label id=\"info\"></label></form></div>";
echo " </div>";
}
else {
echo " </div>";
}
}
} else {
echo "<div class=\"col flex-vcenter-items fw-100 fs-1\"><i class=\"far fa-frown-open pr-3\"></i>Nimaš še nobenih opravil
</div>";
}
First, you will want to fix a lot of your HTML. You have many repeating ID attributes for various HTML elements. This will cause many JavaScript issues and is incorrect syntax for HTML.
$html = ""
$id = $row['id'];
if ($row["naslov"] !== null) {
$html .= "<div class='col-6 flex-vcenter-items fs-1'>\r\n";
$html .= "\tNastavi uro\r\n";
$html .= "\t<form id='form-$id' action='update.php?id=$id' method='POST' data-id='$id'>\r\n";
$html .= "\t\t<input id='cas-$id' class='form-control fancy-border' type='text' name='posodobljeni_cas' />\r\n";
$html .= "\t\t<input id='submit-$id' type='submit' value='Posodobi'> <label id='info-$id'></label>\r\n";
$html .= "\t</form>\r\n</div>\r\n";
$html .= "</div>";
echo $html;
} else {
echo " </div>";
}
You can see a lot being done here. First we create a $html and $id variable to just make things easier. Now when we enter String data into the $html variable, if we're using " (double quote) for wrapping, we can just use $id directly in the string. We will also use ' (single quote) for wrapping all the HTML Element attributes.
Try this for your jQuery:
$(function(){
$("form[id|='form']").on('submit', function(e) {
e.preventDefault();
var form = $(this);
var id = form.data("id");
var cas = $("inptu[id|='cas']", form);
var info = $("input[id|='info']", form);
if(validate()) {
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
});
More Info on the selector: https://api.jquery.com/attribute-contains-prefix-selector/
Unable to test this as you have not provided a testing area. Hope it helps.
You can assign the PHP $row['id']; variable to a local JS variable and append it to the URL as shown below -
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
var id=<?=$row['id'];?>;
$.ajax({
type: "POST",
url: 'update.php?id='+id,
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});

Unable to update div text from ajax response sent via php

Apologies for this question if something out there covers this. I searched and found many relevant posts which has allowed me to get to this point.
I have a form snippet with 1 input box and a button and a div for a status message:
<div>
<div>
<div>
<input id="discount_code"name="discount_code" placeholder=" Enter discount code."></input>
</div>
<div>
<a class="btn btn-xs btn-primary" id="btn-validate">Validate</a>
</div>
</div>
<div id="status_msg" style="border: 1px solid black"></div>
</div>
Then I have the following bits of javascript:
The bit that triggers based on the click:
$('#btn-validate').on('click', function(e) {
e.preventDefault();
validateCode(11); // "11" is a php-provided ID variable
});
The javscript with the ajax call:
function validateCode(eventID) {
var codeValue = $("#discount_code").val();
if (FieldIsEmpty(codeValue)) { // outside function that exists/works fine
$('#status_msg').html('Enter a discount code.').fadeIn(500);
$('#status_msg').fadeOut(2500);
//bootbox.alert("Please enter discount code to validate.");
} else {
$.ajax({
type: 'POST',
cache: false,
async: true,
url: '/include/discount_validation.php',
dataType: 'json',
data: {
event_id: eventID,
discount_code: codeValue
},
beforeSend: function() {
$('#status_msg').html('');
$('#status_msg').fadeIn(0);
},
success: function(data) {
$('#status_msg').html(data);
$('#status_msg').fadeIn(0);
//bootbox.alert(data);
},
error: function(data) {
$('#status_msg').html(data);
$('#status_msg').fadeIn(0);
//bootbox.alert("Error validating discount code: " + JSON.stringify(discount_code));
}
});
}};
And I have a PHP file that, suffice it to say, is working and producing the following json outputs based on the input:
// do php database things...
header('Content-Type: application/json');
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => "$message"));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => "$message"));
}
In the above, I have bootbox.alert lines commented out but when they are active, the box appears and the message is as I would expect it to be.
And lastly, the first condition that triggers if the input box is empty, both fires the alert (when not commented) AND changes the text of #status_msg.
I put the border in to verify visibility and #status_msg is visible but just is not set when either success or error fires.
First check if you getting an object in the response
in the success add
alert(JSON.stringify(data));
If it shows the object then you are good to go else check the php file where you creating the object.
If object is recieved in the success of ajax then you need to parse the json object using jQuery.parseJSON
For Eg:
response = jQuery.parseJSON(data);
Now you have a javascript object with name response.
Now use it
response['status'] or response['message'] in the success of the ajax.
check the code
first discard : " from php code $message variable
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => $message));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => $message));
}
then use the response on font end success function :
success: function(data) {
$('#status_msg').html(data.message);
$('#status_msg').fadeIn(0);
},
Set your data like this inside ajax().
success: function(data) {
var result = eval(data);
$('#status_msg').html(result.message);
$('#status_msg').fadeIn(0);
//bootbox.alert(data);
},
error: function(data) {
var result = eval(data);
$('#status_msg').html(result.message);
$('#status_msg').fadeIn(0);
//bootbox.alert("Error validating discount code: " + JSON.stringify(discount_code));
}
AND
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => $message));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => $message));
}

ajax get Excel form php

I am tryinh to get excel form php through ajax call when i load url of specific php gives me the output but when the same php is called via ajax with some ajax value nothing shows up.. am not sure what to do
ajax:
var fromdate= $("#fromdate").val();
var ToDate= $("#ToDate").val();
var Year= $('#Year').val();
var Category=$('#Category_1').val();
$.ajax({
url: "http://localhost/demo.php",
type: "post",
data: {
fromdate:fromdate,ToDate:ToDate,Year:Year,Category:Category
},
success: function(responsecon) {
window.open('http://YOUR_URL','_blank' );
}
});
PHP:
<?php
$conn=mysqli_connect('localhost','root','0000','xxxxx');
$filename = "users_export";
$fromdate = mysqli_real_escape_string($mysqli,trim($_POST["fromdate"]));
$ToDate = mysqli_real_escape_string($mysqli,trim($_POST["ToDate"]));
$Year = mysqli_real_escape_string($mysqli,trim($_POST["Year"]));
$Category = mysqli_real_escape_string($mysqli,trim($_POST["Category"]));
$sql = "Select * from xxxxxxxxxxx where category='$Category'";
$result = mysqli_query($conn,$sql) or die("Couldn't execute query:<br>" . mysqli_error(). "<br>" . mysqli_errno());
$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t";
$names = mysqli_fetch_fields($result) ;
foreach($names as $name){
}
print ("dasd" . $sep."dasd1" . $sep);
print("\n");
while($row = mysqli_fetch_row($result)) {
$schema_insert = "";
for($j=0; $j<mysqli_num_fields($result);$j++) {
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
Basically there are two problems in your jQuery ajax request:
Sice you are specifying a content-type in your PHP script you have to tell jQuery what to expect from your ajax request using dataType: application/xls in your ajax object.
This is why you don't get any response, because it fails and you have not specified an error callback function to handle the error.
Moreover, in case of success you have to print somehow the content returned from the PHP script with something like $("#selector").html(responsecon);
Here is the updated ajax request:
$.ajax({
url: "http://localhost/demo.php",
type: "post",
dataType: "application/xls", // Tell what content-type to expect from server
data: {
fromdate:fromdate,
ToDate:ToDate,
Year:Year,
Category:Category
},
success: function(responsecon) {
window.open('http://YOUR_URL','_blank' );
$(#"some-container").html(responsecon); // Print the content
},
error: function() {
alert("error");
}
});

AJAX Return for non obtrusive page

I have a form with an id or 'display'. It has one value to send which is a select item that I gave an id of 'services' to.
I want to send the value of 'services' to a function I have created in a seperate php page. The page is called 'functs.php' and the function name is called 'searchResults'.
The 'searchResults' function works, this much I know. It queries a database and outputs 8 seperate php echo statements. I have ran the PHP function and know it works. I know the issues is with my javascript because, well, I am not the greatest at JavaScript and usually shy away from it.
As of right now, the code is not doing anything. My form has its own action to post to a seperate php page.
<form id="display" action="resultPage.php" method="POST">
I am trying to use the javascript/ajax to instantly update the contents of a div BUT if the user has jscript turned off, I want the form to ppost to the alternate page. Here is my jscript.
$(document).ready(function() {
$('#display').submit(function(e) {
var formData = $('#services');
$.ajax({
type: "POST",
url: functs.php,
data: '$formData',
datatype: 'json',
success: function(data) {
if (!data.success)
{
$.amwnd({
title: 'Error!',
content: data.message,
buttons: ['ok'],
closer: 'ok'
});
}
}
});
e.preventDefault();
return false;
});
});
PHP CODE:
<?php
function searchResults()
{
require 'db_config.php';
$sql= "SQL CODE HERE"
$theStyle = <<<HERE
"height:100%;
width:70%;
margin:4% AUTO 0;
padding:1.75em;
font-size:1.25em;
border-radius:5em;
color:white;
background-color:#b72027;
;"
HERE;
while ($row = mysql_fetch_array($result))
{
echo ("<div style = $theStyle>");
echo ("<table>");
echo ("<tr><td>" . $row["0"] . "</td></tr>");
echo ("<tr><td>" . $row["1"] . "</td>");
echo ("<tr><td>" . $row["2"] . ", " . $row["3"] . " " . $row["4"] . "</td></tr>");
echo ("<tr><td>Phone: " . $row["5"] . "</td></tr>");
echo ("<tr><td>" . "" . $row["6"] . "" . "</td></tr>");
echo ("<tr><td>" . $row["8"] . " " . $row["9"] . ", " . $row["10"] . "</td></tr>");
echo ("<tr><td>" . $row["11"] . "</td></tr>");
echo ("<tr><td></td></tr>");
echo ("<tr><td></td></tr>");
echo ("<tr><td>" . $row["7"] . "</td></tr>");
echo ("</table>");
echo ("</div>");
echo ("<br />");
}
}
?>
Your JS code has a couple of issues. The PHP script name needs to be a string inside of quotation marks, and the formData variable has an unnecessary "$." Try this:
$(document).ready(function() {
$('#display').submit(function(e) {
e.preventDefault();
var formData = $('#display').serialize();
$.ajax({
type: "POST",
url: 'functs.php',
data: formData,
datatype: 'json',
success: function(data) {
if (!data.success)
{
$.amwnd({
title: 'Error!',
content: data.message,
buttons: ['ok'],
closer: 'ok'
});
}
}
});
});
});

Categories