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.
Related
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;
});
I have the following AJAX script, but for some reason the var ok it's not returning true or false so the form can continue:
function ajax_call(email,title,url){
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
var ok = true;
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if(response == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
}
});
return ok;
}
HTML:
<form onsubmit="return ajax_call();">
...
</form>
PHP:
<?php
//////....
if(!empty($errors)) {
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
} else { echo 'bien'; }
?>
Everything works good, except for the return value.
Thanks in advance.
Prevent the submit completely, send the ajax request, then if it's good, submit the form.
HTML:
<form id="myform">
...
</form>
JavaScript:
$("#myform").submit(function(e){
// prevent submit
e.preventDefault();
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
context: this,
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if($.trim(response) == 'bien') {
this.submit(); // submit, bypassing jquery bound event
}
else {
$("#ajax_call").html(response);
}
}
});
});
You are returning ok at the end of your function. This is returned before your ajax request is sent and completed.
You cannot rely on the return value of your function, you should do something inside your "success" part. It basically depends on what you want to do with your return value
I'm a complete newbie to jquery but in some of the scripts I've been working on I've had to prefix the 'response' you have.
For instance...
if(response.tiitle == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
Also be aware you have double letters in your "parametros" but I'm sure that was intentional (i.e. tiitle and not title etc).
I just started picking up JQuery today, and for some reason I can't get this simple $.post to work when a form is submitted.
I want to pass the value of 2 as star to my PHP page "update_item.php".
I added an alert and saw that when I clicked submit it would give me the alert, but for some reason the value of 2 just doesn't pass to the php page.
Here's what I have with JQuery:
$('#form_edit_item').submit(
function(){
alert("submitting");
$.post(
"edititem.php",
{star: "2"},
);
});
Here's what I have in update_item.php:
$star = $_POST['star'];
echo "Star value: " .$star. "";
What am I doing wrong?
Your help would be very much appreciated! Thanks!
$.post(url, data, callback, "json");
http://docs.jquery.com/Ajax/jQuery.post
$('#form_edit_item').submit(
function() {
alert("submitting");
$.post("update_item.php", {
star : "2"
});
});
Remove the trailing comma after {star : "2"}. Try this.
You could use ajax
$.ajax({
type: "POST",
url: "update_item.php",
data: {
star: "2" // or 'star: $('#id').val()', or any other value
}
}).done(function( msg ) {
// do it when its done or do nothing
});
and in update_item.php you should use somthing like that
<?php $star=(isset($_POST['star']) ? $_POST['star'] : '');
echo $star; ?>
If this won't work, try change POST to GET so you can check passing value by url (domain.com/update_item.php?star=2)
You can Use this code,
<form action="../handler/AjaxHelper.php" method="POST">
</form>
$(document).ready(function() {
$('form').submit(function() {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(data)
{
var result = $.parseJSON(data);
if (result["messageCode"] == 'success')
{
alert(result["message"]);
}
else
{
alert(result["message"])
}
},
error: function()
{
alert("Please Try Again");
}
});
return false;
});
});
In AjaxHelper.php
$objLoginHelper = new LoginHelper();
$objLoginHelper = unserialize($_SESSION["LoginInformation"]);
$postDate = date("Y-m-d H:i:s", strtotime($_POST['txtTopicDate']));
$dataTopics = array($_POST['txtTopicSubject'], $postDate, $_POST['ddlCategories'], $objLoginHelper->getUserLoginId());
$result = array();
try {
$rp = new Repository();
$rp->SaveForumTopics($dataTopics);
$result["messageCode"] = "success";
$result["message"] = "Category Save Successfully";
} catch (Exception $ex) {
$result["messageCode"] = "error";
$result["message"] = $ex->getMessage();
}
echo json_encode($result);
i have two separate javascipt file and a php file, on the first create.js i send the variables to the get.php file using post, and then i want to send those variables from get.php to the register.js, how can i get those variables in the register.js and use them to the next step?
this is the code from the first js file:
var fs = $('#fname').val();
var ls = $('#lname').val();
var name = $('#adduser').val();
var pass = $('#addpass').val();
var cpass = $('#conpass').val();
if (document.forms['form2'].fname.value == "" || document.forms['form2'].lname.value == "" || document.forms['form2'].adduser.value == "" || document.forms['form2'].addpass.value == ""){
alert("Input the required Filled!");
}
else{
var vals;
var request = $.ajax({
url:"ifexist.php", type:"POST",
data:{
n:name
}
});
request.done(function(data){
vals = data; //alert(data);
if (vals == "1"){
alert("Username Already Exist!");
}
else
if(pass==cpass){
var request1 = $.ajax({
type: "POST",
url:"get.php",
data:{ fi:fs, la:ls, na:name, pa:pass}
});
request1.done(function(data){
alert("Not yet!");
location.href = 'captcha.html';
// setTimeout(function() {location.href = 'captcha.html';},1500);
});
}
else
alert("Password did not match!");
});
}
and this is the second js file:
$.getJSON('get.php', function(data) {
// Inside your success callback:
var fir = $("#fi").html(data.uf);
var las = $("#la").html(data.ul);
var nam = ("#na").html(data.un);
var pas = $("#pa").html(data.up);
alert("Success!");
var request = $.ajax({
type: "POST",
url:"adduser.php",
data:{ f:fir, l:las, n:nam, p:pas}
});
request.done(function(data){
alert("Success!");
//setTimeout(function() {alert("Success!");},1500);
});
});
and this is the php file:
<?php
$uf = $_POST['fi'];
$ul = $_POST['la'];
$un = $_POST['na'];
$up = $_POST['pa'];
//add to associative array
$result['fi'] = $uf;
$result['la'] = $ul;
$result['na'] = $un;
$result['pa'] = $up;
// encode as json and echo
echo json_encode($result);
?>
You can't do that (send request to browser. well technically you can as push service but that's not what you need IMHO and PHP is tricky in dealing with that) .
why don't you communicate directly within JavaScript after your ajax POST call gets completed? I mean, what do you want to send to register.js?? (don't forget that even though they are separate files they can talk to each other as they are all included)
var post_data = { f:fir, l:las, n:nam, p:pas};
var request = $.ajax({
type: "POST",
url:"get.php",
data:post_data
});
request.done(function(data){
alert(data); //will give you objects the -response form the server
// now do whatver you need to do, cal an fucntion to create.js, create trigger, etc.
});
I am using this tutorial http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_slide_toggle
Here is the code without the style.
<script type="text/javascript">
$(document).ready(function()
{
$(".flip").click(function()
{
var panel = "open";
$(".panel").slideToggle("slow");
});
});
</script>
How would I go about saving the state of this so if I refreshed the page it would remain open or closed. I imagine a php session would be the correct way, but how do I write that in the javascript?
In JS:
var readWirite='write'; //or 'read'
$.ajax({
type: "POST",
url: "myPhpFile.php",
data: "panel="+panel+"&readWrite="+readWrite;
success: function(msg){
if(msg == '1'){
alert('Horay panel saved!');
} else {
$('#panelId').html(msg); //Write saved panel back to html
}
}
});
In myPhpFile.php:
<?php
if(!isset($_SESSION)) session_start();
if(isset($_POST['readWrite']) && isset($_POST['panel'])){
if($_POST['readWrite'] == 'write'){
$result = '0';
if($_SESSION['panel'] = $_POST['panel']) $result = '1';
echo $result;
} else if($_POST['readWrite'] == 'read') {
echo $_SESSION['panel'];
}
}
?>