Controller Script not Able to Get AJAX Data - php

I am trying to pass serialized form data to a PHP controller with jQuery. On successful processing, the user will be redirected to a results page. I am not seeing any redirect taking place which tells me something is wrong with my controller. I am seeing a sucessful AJAX callback.
The parameters are 'zipcode' and 'token'. The controller will validate the token, die if invalid, or perform the necessary logic once if valid.
I cannot find anything that stands out as incorrect about my code and could use an extra set of eyes.
HTML
<form action="" class="zipsearchform">
<div class="form-group">
<h2>Search by Zip Code</h2>
<label for="zip-search-field">Enter a Zip Code</label>
<input type="text" class="form-control" id="zip-search-field" name="zipcode">
<br>
<input type="hidden" name="token" value="<?php if (isset($token)) echo $token; ?>">
<button type="submit" class="btn btn-default zipsubmitbtn">Find Notaries</button>
</div>
</form>
JS
$('.zipsubmitbtn').on('click', function(){
event.preventDefault();
var params = $('form.zipsearchform').serialize();
$.ajax({
type: 'post',
url: 'parseByZip.php',
data: {paramString: params},
async: true,
success: function(){
alert(params);
}
});
});
PHP Controller
<?php
include_once 'resources/functions.php';
$zipcode = $_POST['zipcode'];
$token = $_POST['token'];
if (validate_token($token) && isset($zipcode)) {
$pattern = '/^\d{5}([\-]?\d{4})?$/';
if (preg_match($pattern, $zipcode)) {
$radius = 25;
include_once 'resources/apizip.php';
header("Location: notaries.php?lat=$latitude&lon=$longitude&distance=$radius");
} else {
echo "Zip code field cannot be empty and zip code must have the proper format of 00000 or 00000-0000";
}
} else {
echo 'Unable to handle your request right now.';
}

Related

Try to using ajax form instead of form action (solve)

I would like to improve user experience at my website. So I try to change the form action ajax, and I has been try some tutorial but I still getting stuck.
I am using a php forum program/source code call !Discuz and it was from China. Below is my coding now.
In html.
<form method="post" id="jnfarm_pop" action="plugin.php?id=cc&do=shop">
<input type="hidden" name="shopsubmit" value="yes">
<!--first item-->
<input type="checkbox" name="jsid[1]" value="1">
<input type="number" style="width:3em;" name="qty[1]">
<!--second item-->
<input type="checkbox" name="jsid[2]" value="1">
<input type="number" style="width:3em;" name="qty[2]">
...continue 50 item
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn">submit</button>
</form>
in PHP, file name plugin.php
<?php
if($_GET['id'] == 'cc'){
if(submitcheck('shopsubmit')){ //core function in !Discuz
for($x=1;$x<=50;$x++){
if($_GET['jsid'][$x] == '1'){
$qty[$x] = intval($_GET['qty'][$x]);
//process....
}
}
showmessage('message here','redirectlink');//this is !Discuz program function and it is fine.
}
}
?>
The above script is working fine while using form action, and redirect to my output page. If I would like to change to ajax, how do I adjust the below source code?
<script type="text/javascript">
function login() {
$.ajax({
type: "POST",
dataType: "json",//? is it can use json? since my form data can get as array
url: "plugin.php?id=cc&do=shop" ,//url
data: $('#jnfarm_pop').serialize(),
success: function (result) {
console.log(result);
if (result.resultCode == 200) {
alert("SUCCESS");
}
;
},
error : function() {
alert("ERROR");
}
});
}
</script>
<form method="post" id="jnfarm_pop" action="plugin.php?id=cc&do=shop">
<input type="hidden" name="shopsubmit" value="yes">
<!--first item-->
<input type="checkbox" name="jsid[1]" value="1">
<input type="number" style="width:3em;" name="qty[1]">
<!--second item-->
<input type="checkbox" name="jsid[2]" value="1">
<input type="number" style="width:3em;" name="qty[2]">
...continue 50 item
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login()">submit</button>
</form>
And is it have to adjust the plugin.php source code?
Updated, below is work for me, thanks fayis003.
html change the <script></script>
$.get('plugin.php?id=cc&do=shop', $('#jnfarm_pop').serialize(), result => {
//alert('success');
console.log(result); // check the result in console and if you can see it as a JS object you don't need to parse
result = JSON.parse(result); // Parse is required if you return the result as plain text otherwise you can omit this step in case you are returning the result as content type json
alert(result.final);//alert message here
location.href = result.link;// if you need to get redirected
}).fail(result => {
alert('fail');
});
PHP
<?php
if($_GET['id'] == 'cc'){
if(submitcheck('shopsubmit')){ //core function in !Discuz
for($x=1;$x<=50;$x++){
if($_GET['jsid'][$x] == '1'){
$qty[$x] = intval($_GET['qty'][$x]);
//process....
}
}
$final = 'message here';
echo json_encode(['final' => $final]);
}
}
?>
You can not initiate a direct browser redirect using server-side code on ajax request like you do with synchronous requests. instead, you have to return a URL to which you want to get redirected to and then do something like location.href = result.link in the result callback.
for ajax request, the simplest option is using as follows
$.get('plugin.php?id=cc&do=shop', $('#jnfarm_pop').serialize(), result => {
//alert('success');
console.log(result); // check the result in console and if you can see it as a JS object you don't need to parse
result = JSON.parse(result); // Parse is required if you return the result as plain text otherwise you can omit this step in case you are returning the result as content type json
let final = result.final;
location.href = result.link;// if you need to get redirected
}).fail(result => {
alert('fail');
});
now in the server-side code instead of creating a redirect from PHP return something like
return json_encode(['link' => 'somlink']);
of just return success message as usual.

redirect page after jquery submit using header() function on another page using php

i have this login form
<form autocomplete="off" id="login_form">
<div class="login-wrapper">
<input required type="text" class="login-input" name="email" id="email" placeholder="email">
<span class="fas fa-envelope mail_name-email"></span>
<span class="err_output err_email"></span>
</div>
<div class="login-wrapper">
<input required type="password" class="login-input" name="pwd" id="pwd" placeholder="password">
<span class="fas fa-lock pwd_password"></span>
<span class="err_output err_pwd"></span>
</div>
<input type="submit" class="login_btn" id="login_btn" name="login" value="log in">
</form>
the submission is handled using jquery, like so
$(document).ready(function() {
$(document).on("submit", "#login_form", function() {
Login();
//send values to post
const mail = document.getElementById("email").value;
const pwd = document.getElementById("pwd").value;
$.ajax({
type: "POST",
url: "./inc/login.php",
data: {
email: mail,
password: pwd
}
});
return false;
});
});
so it works well but i wanted to do all the validation on the serverside particluarly in the login.php file included in the url within the jquery code because the data entered is sensitive and i cannot just redirect usin javascript. So even before i started the validation i tried a redirect to another page after the form was submitted but it wouldn't work, i tried header("Location: ../main.php") and echo "<script>location='../dashboard.php'</script>"; but on the console all i saw was this
jquery.js:9837 XHR finished loading: POST "http://localhost/My%20portfolio/admin/inc/login".
i have even included an action attribute on my form pointing to the action page but it doesn't work, this is the only way i can proceed with validation otherwise i am stuck, i dont know what's wrong
You can't use a redirect in PHP on an ajax call. You need to return something to the JS page and redirect from there. For example, your PHP can return a json object with the status and the URL to forward to.
You can output something like this:
{
"status" : "success",
"url" : "http://www.example.com/url-to-redirect"
}
Or if it fails
{
"status" : "error",
"message" : "Error message to show"
}
Then in your javascript, check for the answer and validate the status
$.ajax({
type: "POST",
url: "./inc/login.php",
data: {
email: mail,
password: pwd
},
dataType: "json"
}).done(function( data ) {
if (data.status === "success") {
window.location.href = data.url;
}
else if (data.status === "error") {
alert(data.message);
}
});
In your PHP script you need to output something like an array.
So in your PHP validation, if everything is validated, you can simply do
echo json_encode(array('status' => 'success', 'url' => 'http://www.example.com/url-to-redirect'));
But if it fails:
echo json_encode(array('status' => 'error', 'message' => 'Error message to show'));
I suggest you read more on json_encode and ajax calls with PHP.

Submit form using ajax: Was working, now not working?

I have the following HTML form in signup.php:
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
I am trying to submit the form using ajax, without page refresh:
<!-- include files -->
<?php include 'assets/config.php';?>
<?php if(isset($_SESSION["CUSTOMER_ID"])){
header('Location: myaccount.php'); } ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('assets/login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
I am posting the form to do_signup_check.php and running a query to see if the user is already registered. echo 1 for a positive result and 0 for a negative result:
Do_Signup_Check.php:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn)); }
if(mysqli_num_rows($check) > 0){
echo '1';
}else{
echo '0';
}
?>
If the result is 0 then the ajax should load my page do_signup.php.
But alas it is not getting this far. It was working and then i switched off the computer and came back to it and now it won't work.
Please can someone show me where I've gone wrong?
if(result == 0){ here result is not using in success function:
you must need to pass resultant variable here:
success: function () {
as:
success: function (result) {
Now, you can use your condition if(result == 0){
Second, i suggest you to pass dataType: 'html' in your ajax request.
Edit:
You are using <?php if(isset($_SESSION["CUSTOMER_ID"])){ line in your code, if you are not using session_start() in your code then this check will not work.
For this line data:{"name":name,"email":email}, i didnt see name and email in your code, where you define these 2 variables which you are using in your ajax params.

How to use $.ajax function properly?

I don't know how to run $.ajax properly. I usually make all xmlHTTP objects manually using javascript and then use jQuery wherever required. So please help me use this function properly in jQuery.
HTML
<form action="login.php" method="post" onSubmit="return login()" >
<input type="text" name="eMailTxt" id="eMailTxt" placeholder="Email Address" />
<input type="password" name="passWordTxt" id="passWordTxt" placeholder="password" />
<br />
<p><!--wanna show password does not match here--></p>
<input type="submit" value="Login" id="submitBtn" class="Btn" />
</form>
JQuery Ajax
function login()
{
$email = $("#eMailTxt").val();
$pass = $("#passWordTxt").val();
$.ajax({
url:'loginCheck.php',
type:'POST',
data:{q:$email,s:$pass},
success:function(response){
$("#loginForm p").innerHTML = xmlhttp.responseText;
return false; //is this the correct way to do it?
}
});
return true; //not really sure about this
}
PHP MySQL
$q=$_POST["q"];
$s=$_POST["s"];
$con=mysqli_connect("localhost","root","","SocialNetwork");
$check="SELECT PassWord FROM people WHERE EMAIL = '".$q."'";
$data=mysqli_query($con,$check);
$result=mysqli_fetch_array($data);
if ($s != $result)
{
echo "Password does not match";
}
jQuery object doesn't have a property innerHTML which is used on DOM element. Use method html() instead:
$("#loginForm p").html(response);
Or you could refer to DOM element like that:
$("#loginForm p")[0].innerHTML = response; // equivalent to .get(0)
Be aware as ajax is async by default, your login function here will always return true.
BTW, response here corresponds to the returned value from server, not the jqXHR object (xhr object wrapped inside a jquery object).
UPDATE
function login(form)
{
$email = $("#eMailTxt").val();
$pass = $("#passWordTxt").val();
$.ajax({
url:'loginCheck.php',
type:'POST',
data:{q:$email,s:$pass},
success:function(response){
if(response === "Password does not match") {
$("#loginForm p").html(response);
return false;
}
//if password match, submit form
form.submit();
}
});
//we always return false here to avoid form submiting before ajax request is done
return false;
}
In HTML:
<form action="login.php" method="post" onSubmit="return login(this)" >
HTML
<form action="login.php" method="post" class="js-my-form">
<input type="text" name="record[email]" id="eMailTxt" placeholder="Email Address" />
<input type="password" name="record[password]" id="passWordTxt" placeholder="password" />
<br />
<p><!--wanna show password does not match here--></p>
<input type="submit" value="Login" id="submitBtn" class="Btn" />
</form>
jQuery
$(document).ready(function () {
$('.js-my-form').submit(function () {
var data = $(this).serialize();
var action = $(this).attr('action');
var methodType = $(this).attr('method');
$.ajax({
url: action,
type: methodType,
data: data,
beforeSend: function () {
//Maybe Some Ajax Loader
},
success: function (response) {
// success
},
error: function (errorResponse) {}
});
return false; //Send form async
});
});
PHP
if (isset($_POST['record']) {
//Your PHP Code
} else {
header("HTTP/1.0 404 Not Found"); // Trow Error for JS
echo 'invalid data';
}
Ajax success call back contains only data (you are confused with the compete function of ajax or pure javascript xmlhttp request)
therefore
success:function(response){
$("#loginForm p").html(response);
}
Also seeing your query you are susceptible to sql injection

Ajax Data Posting

Hello im trying to implement an ajax invitation script which will let the user to invite his/her friends to that event. I use the mostly same javascript in the other parts of the website and they work perfect, but in this case, it doesn't work, i'm sure that the problem persists because of the javascript part, because as i said, i use the nearly exact script and it works perfect, when i post the data, it doesn't send the email, my mail function works good ( in other pages i use the same without ajax and it works ) but i think the javascript part can't post the data in this case.
By the way there is not any problem with getting the values in the hidden parts.
Hope you can help.
the javascript part :
<script type=\"text/javascript\">
$(document).ready(function() {
$('.error').hide(); //Hide error messages
$('#MainResult').hide(); //we will hide this right now
$(\"#button\").click(function() { //User clicks on Submit button
var js_name = $(\"#name\").val();
var js_message = $(\"#message\").val();
var js_username = $(\"#username\").val();
var js_useremail = $(\"#useremail\").val();
var js_eventname = $(\"#eventname\").val();
if(js_name==\"\"){
$(\"#nameLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
if( js_message==\"\"){
$(\"#messageLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
var myData = 'postName='+ js_name + '&postMessage=' + js_message + '&username=' + js_username + '&useremail=' + js_useremail + '&eventname=' + js_eventname;
jQuery.ajax({
type: \"POST\",
url: \"invite.php\",
dataType:\"html\",
data:myData,
success:function(response){
$(\"#MainResult\").html('<fieldset class=\"response\">'+response+'</fieldset>');
$(\"#MainResult\").slideDown(\"slow\"); //show Result
$(\"#MainContent\").hide(); //hide form div slowly
},
error:function (xhr, ajaxOptions, thrownError){
$(\"#ErrResults\").html(thrownError);
}
});
return false;
});
$(\"#gobacknow\").live(\"click\", function() {
$(\"#MainResult\").hide(); //show Result
$(\"#MainContent\").slideDown(\"slow\"); //hide form div slowly
//clear all fields to empty state
$(\"#name\").val('');$(\"#message\").val('');
});
$(\"#OpenContact\").live(\"click\", function() {
$(\"#form-wapper\").toggle(\"slow\");
});
});
</script>
the html part:
<div id="form-wapper">
<div id="form-inner">
<div id="ErrResults"><!-- retrive Error Here --></div>
<div id="MainResult"><!-- retrive response Here --></div>
<div id="MainContent">
<fieldset>
<form id="MyContactForm" name="MyContactForm" method="post" action="">
<label for="name" id="nameLb">Email : <span class="error" style="font-size:10px; color:red;">Error.</span></label>
<input type="text" name="name" id="name" />
<label for="message" name="messageLb" id="messageLb">Message : <span class="error" style="font-size:10px; color:red;">Error.</span></label><textarea style="resize:vertical;" name="message" id="message" ></textarea>
<input type="hidden" name="username" id="username" value="<?php echo get_username($userid); ?>">
<input type="hidden" name="useremail" id="useremail" value="<?php echo get_email($userid); ?>">
<input type="hidden" name="eventname" id="eventname" value="<?php echo $eventname; ?>">
<br><button id="button">Send</button>
</form>
</fieldset>
</div>
<div style="clear:both;"></div>
</div>
invite php file :
$postName = filter_var($_POST["postName"], FILTER_SANITIZE_STRING);
$postMessage = filter_var($_POST["postMessage"], FILTER_SANITIZE_STRING);
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
$useremail = filter_var($_POST["useremail"], FILTER_SANITIZE_STRING);
$eventname= filter_var($_POST["eventname"], FILTER_SANITIZE_STRING);
invite($useremail, $postMessage , $username, $eventname, $postName); // this is a functipon that i use, it works in other cases, but not working in here
Rather than trying to debug that javascript, here is a much much easier / cleaner way to do this for the javascript AJAX post:
$.post('invite.php',$('#MyContactForm').serialize(),function(data){
if(data.success){
// all your on success stuff here
alert('success!');
}else{
// show error messages
alert(data.e);
}
},'json');
For your PHP part, echo a JSON response array, eg:
$data['success']=false;
$data['e']='Some error';
echo json_encode($data);

Categories