Pass data from ajax to php [duplicate] - php

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Ajax:
function check_user_country_prod(userId , countryCode , testType )
{ //using alert to check that all data are correct
$.ajax({
type: "POST",
url: "http://localhost/test/testForm.php",
data: { userId: userId ,
countryCode : countryCode ,
productCode: testType
},
success:function(res) {
if(res == "OK")
return true;
else
return false;
}
});
}
PHP:
<?php
require_once("Connections/cid.php");
$userId= $_POST['userId'];
$productCode= $_POST['productCode'];
$countryCode= $_POST['countryCode'];
$sql_check = "SELECT * FROM utc WHERE userId = '$userId' AND productCode = '$productCode' AND countryCode = '$countryCode'";
$list = mysqli_query( $conn, $sql_check);
$num = mysqli_fetch_assoc($list);
if($num >0)
echo "OK";
else
echo "NOK";
?>
I am very sure that the data i had pass in to the php file are correct. However i cant seem to get my data to the php file and it keep return false value back to me. Anything i can do to make it works?
**Note: Somehow even if i change both result to return true in ajax, it will still return false.
and i tried to change the link to another file with only echo "OK"; but it also doesn't work. So i think it is not the file problem. It just never run the ajax no matter what. Do i need to do any link for ajax to run? **

function check_user_country_prod(userId , countryCode , testType )
{ //using alert to check that all data are correct
$.ajax({
url: "test/testForm.php"
type: "POST",
url: "http://localhost/test/testForm.php", // This needs to be "test/testForm.php"
data: { userId: userId ,
countryCode : countryCode ,
productCode: testType
},
success:function(res) {
if(res == "OK")
return true;
else
return false;
}
});
}

Adjust this code according your input type. I hope this will help you:
$(document).ready(function() {
$("#submit_btn").click(function() {
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_phone = $('input[name=phone]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if(user_name==""){
$('input[name=name]').css('border-color','red');
proceed = false;
}
if(user_email==""){
$('input[name=email]').css('border-color','red');
proceed = false;
}
if(user_phone=="") {
$('input[name=phone]').css('border-color','red');
proceed = false;
}
if(user_message=="") {
$('textarea[name=message]').css('border-color','red');
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userMessage':user_message};
//Ajax post data to server
$.post('contact_me.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$('#contact_form input').val('');
$('#contact_form textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function() {
$("#contact_form input, #contact_form textarea").css('border-color','');
$("#result").slideUp();
}); });

Try this also both are running on my localhost:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function (d) {
alert(d);
}
});
});
});
</script>
<form method="post" id="myform">
<input type="text" name="time" /><br>
<input type="text" name="date" /><br>
<input name="submit" type="submit" value="Submit">
</form>
make new file of post.php and pest this code. This code will alert your input field value:
<?php print_R($_POST); ?>

"my current folder is localhost/abc/bsd.php while the one that i am going is localhost/test/testForm.php".
From the above comment, you have to change the ajax url to
url: "/test/testForm.php",
Apart from this , your php code shows
$num = mysqli_fetch_assoc($list);
if($num >0)
echo "OK";
This is incorrect as mysqli_fetch_assoc returns an associative array of strings. So, the comparison $num >0 is illogical.

Related

form is getting submitted with unbind

<script type="text/javascript">
//$('#student').change(function() {
$('#but').click(function() {
var payid = $("#feType").val();
var course = $("#course").val();
var course_id = $("#course_id").val();
var stud_id = $("#student").val();
var paid_amt1 = $("#paid_amt").val();
var serializedData = $("form").serialize();
$.ajax({
dataType: "json",
url: '<?php echo ADMINPATH;?>student/getNewFee/'+payid+'/'+course_id+'/'+stud_id+'/'+course,
data: '',
async: true,
success: function(data){
if(data == false){
$("form").unbind('submit').submit();
alert("This student doesn't have transport");
return false;
}
var result = data;
if(Number(result) >= Number(paid_amt1)){
$("#fee_data").submit(function(){
return true;
});
}else {
$("form").unbind('submit');
alert("Due Amount is less than paid amount");
return false;
}
}
});
});
</script>
If the data is coming to if condition the form has to submit, and if data is coming to else condition form submitting should stop. "if" condition is working well, but coming to else the form is still getting submitted.
You are calling submit() method from else portion.
Remove below code from else portion.
$("form").unbind('submit').submit();
Remove this line, it is not needed and you are triggering the submit with it:
$("form").unbind('submit').submit();
If you only want to remove the on submit callback, you can do this:
$("form").unbind('submit');
You need to add a return false before the end of the click event:
$('#but').click(function() {
// ....
return false;
});

How to run PHP with Ajax to validate results?

I'm making a Ajax script which validates results with PHP file before processing. Below is my Ajax script but I don't understand how to retrieve this DATA to validate.php and how to get results back from my PHP file.
<script>
function shake(){
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(),
success: function(data){
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
How can I process this Ajax script with validate.php ?
Can it be like:
<?php
// Get values from AJAX
$userid = $_GET['userID'];
$pass = $_GET['pw'];
?>
What results is this Ajax script expecting? I see resultado==0
So my question is how can I send resultado=1 with PHP to this script?
Should it be:
<?php
// Send result to AJAX
$resultado = 1;
?>
Thank you for helping.
I think this is what you're asking for.
The php script at the bottom is missing the closing tag for a reason.
In the success function, after you parse the result into a json object, you can reference the members with a '.' E.G result.varName
<script>
function shake()
{
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else
{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: {userID: $("#userID").val(), pw: $("#pw").val()},
success: function(data){
try
{
var result = $.parseJSON(data);
// result is now a JSON object
}
catch (e)
{
alert("JSON Parsing Failed on" + data );
return 0;
}
console.log(result);
if(result.isValid === 1){
// do something
}
alert(result.Message);
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else
{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
<?php
if( !isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] != 'POST')
{
exit;
}
if( !isset($_POST['userID']) || !isset($_POST['pw']) )
{
// need more validation than this
exit;
}
$output = array();
$output['isValid'] = '1';
$output['Message'] = 'Data transfered';
$output['moreData'] = false;
echo json_encode($output);
Change data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(), to:
data: {userID: $("#userID").val(), pw: $("#pw").val()}
Also, I'd recommend setting userID and pw vars before passing it in as it is easier to read and easier to maintain.

PHP Ajax post result not working

I am trying to get a form to work, but when I call ti with ajax, it will not work.
// ----------------------------EDIT----------------------------
I actually found exactly what I was looking for while browsing around.
jQuery Ajax POST example with PHP
I just have one question, would this be the best way to get the data, or could I call it from an array somehow?
post.php
$errors = array(); //Store errors
$form_data = array();
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$_POST['name'])); //Get data
if (!empty($errors)) {
$form_data['success'] = false;
$form_data['errors'] = $errors;
} else {
$form_data['success'] = true;
$form_data['country'] = $query['country'];//Have a bunch of these to get the data.
$form_data['city'] = $query['city'];//Or is there an easier way with an array?
$form_data['zip'] = $query['zip'];
// Etc, etc
}
echo json_encode($form_data);
Then in index.php just call it via:
$('.success').fadeIn(100).append(data.whatever-i-have-in-post);
// ----------------------------v-ORIGINAL-v----------------------------
This is I have so far. At the bottom you can see I have an if statement to check if I could get the results from post, but it always results in "unable to get country" (I'm checking with google.com). I don't know if I am doing it correct or not. Any ideas?
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString
});
}
return false;
});
});
</script>
<form id="form" method="post" name="form" style="text-align: center;">
<input id="name" name="name" type="text">
<input class="submit" type="submit" value="Submit">
<span class="error" style="display:none">Input Empty</span>
<?php
include_once('post.php');
if($query && $query['status'] == 'success') {
$query['country'];
} else {
echo 'Unable to get country';
}
?>
</form>
Post.php
$ip = $_POST['name'];
//$ip = isset($_POST['name']); // I dont know if this makes a difference
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
Try with this after changing the dataString = {name: name}
$(".submit").click(function() {
var name = $("#name").val();
var dataString = {name: name};
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(response) {
// Grab response from post.php
}
});
}
return false;
});
The best way i like to grab the JSON data from ajax request. You can do it by slightly changes in your script.
PHP File
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
echo json_encode(array('status'=>true, 'result'=>$query)); // convert in JSON Data
$(".submit").click(function() {
var name = $("#name").val();
var dataString = {name: name};
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
dataType: 'json', // Define DataType
success: function(response) {
if( response.status === true ) {
// Grab Country
// response.data.country
// And disply anywhere with JQuery
}
}
});
}
return false;
});

Form Validation To Send Only If Username Doesn't Exist

I've created a JQuery script that checks a database for usernames and shows an error if you type in an existing name on keyup, this is workng fine but the form still submits even if this error is true. What other code can I add to check that this error doesn't exist? Here is the code I have so far:
<script>
$(function()
{
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Thank you
please see the comments on the code
assuming that the data == 1 means that the name is already registered and you will show an error
<script>
$(function()
{
var name = false; // a variable that holds false as the initial value
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
name = true; // on success , if the name isnt there then assign it to true
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username) && name == true) // check for the value of name
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Instead of checking the username against the regex, you should check the status of $('.usernameStatus') because it is possible that it passes the regex test but still fails the duplicate test returned from your db.
So
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
should instead be:
$('#registerButton').click(function()
{
var username=$("#username").val();
if(!$('.usernameStatus').hasClass('error'))
{
Even better would be to introduce a variable that holds the validity of the name field so you don't need to get the DOM Element all the time and check it's class.
I think your error might be because of a bad data syntax
It should be like this:
data: 'username:'+ username,
Debug your PHP code to see if its receiving the username properly at the moment though

JQuery POST showing as empty array in PHP script

In a JS file I am performing this function:
$(function() {
$(".button").click(function() {
//get the button's ID (which is equal to its row's report_id)
var emergency = this.id;
var button = this.attributes['name'].value;
var dataString = 'reportid=' + emergency;
alert(dataString);
if (button == "clockin") {
$.ajax({
type: "POST",
url: "/employeetimeclock.php",
data: dataString,
success: function() {
window.location = "/employeetimeclock.php";
}
});
} else if (button == "closereport") {
var r = confirm("Are you sure you want to close this report?\nThis action CANNOT be undone!");
if (r == true) {
$.ajax({
type: "POST",
url: "/closeemergencyreport.php",
data: dataString,
success: function() {
alert("Report Successfully Closed!");
window.location = "/closeemergencyreport.php";
},
error: function() {
alert("An error has occured, the report was not closed");
}
});
} else {
alert("Report was not closed.");
}
}
});
});
For the else if (to closeemergencyreport.php) the code in that php script is as follows:
<?php
require_once("models/config.php");
require_once("models/header.php");
require_once("models/dbconnect.php");
$reportid = $_POST['reportid'];
var_dump($_POST);
$sql = "UPDATE emergency_report SET report_closed = '1' WHERE report_id IN ( $reportid )";
//execute and test if succesful
$result = mysql_query($sql) or die(mysql_error());
if($result){
} else{
}
?>
I've done this same exact thing on 3 other pages and it works flawlessly however this is giving me trouble where on that php script the VAR_DUMP is saying it's returning an empty array. I've been reading and rereading the code for about an hour and a half now so I think i'm burnt out and need to have an outside view. Ive been all over the site and no one has had a solution that worked for me.
I know it's posting because fire bug is showing this on the form's page that the javascript is run on:
http://i.imgur.com/hItdVU1.png (sorry cant post images yet)

Categories