Ajax script writing - php

I have this code for example
<?php
if(isset($_POST['goose'])){
echo '<div>goose</div>';
}
?>
<form action="goose.php" method="POST">
<input type="submit" name="goose" />
</form>
How can I write something like this but in AJAX? I don't know this language.

I recommend using jQuery.
$.ajax({ // begins our async AJAX request
type: "POST", // defining as POST
url: "goose.php", // page to request data from
data: ["goose":$("input[name=goose]").val()], // define POST values
success: function(output){
alert(output);
},
error: //do something else
});
Because we have set the type to POST our data will need to be in the form of an associative array with "goose" being equivalent to $_POST["goose"].
data: ["goose":$("input[name=goose]").val()],
The success is what will happen if the data is able to be sent correctly with output being what is returned. In our case output = <div>goose</div>.
success: function(output){
alert(output);
}
error can also have a function but here you will want to tell the script what do do if say goose.php is un-reachable.

No need for extra frameworks. Just use fetch api.
<form action="goose.php" method="POST" onsubmit="submit(event, this)">
<input type="submit" name="goose" />
</form>
Javascript:
function submit(event, form) {
event.preventDefault();
fetch(form.action,{
method: 'post',
body: new FormData(form)
}).then((data) => {
console.log(data);
});
}

Related

Getting Json data from jquery ajax to php and redirect the page

I have written front end simple login application using Jquery, ajax and json, I want to send json information to php and it has to retrieve the data of json and if successful it has to redirect to another page, Here is the simple front end code I am using.
!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="login.css">
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("#submit").on('click',function(){
var person={
user:$("#user").val(),
pass:$("#pass").val(),
}
$.ajax
({
type: "POST",
url: '/test/login.php',
dataType: 'json',
async: false,
data: person,
success: function () {
}
})
});
});
</script>
</head>
<body>
<div id="loginstyle">
<form action="login.php" method="post">
<table>
<tr>
<td>
Email:</td><td><input type="email" name="email" id="user" ></td>
<tr><td>Password:</td><td><input type="password" name="password" id="pass"><td></tr>
</table>
<input type="submit" value="submit" id="submit">
</div>
</form>
</body>
</html>
Can anybody suggest me how to decode the json data and print the user and pass in login.php
You have to do it this way
$.ajax
({
type: "POST",
url: '/test/login.php',
dataType: 'json',
async: false,
data: person,
success: function (data) {
var res = $.parseJSON(data);
//DO SOMETHING WITH res
//IF res is some value, redirect, otherwise not.
}
});
1st: You can use e.preventDefault() while submit to prevent reloading the page
$("#submit").on('click',function(e){
e.preventDefault();
2nd: while you use type: "POST", and pass user: and pass: you need in php
<?php
echo($_POST['user']);
echo($_POST['pass']);
?>
and in ajax success callback function
success: function (data) {
alert(data);
}
in this case maybe no need to use json as a dataType
3rd : It will be good to Take a look at
What does "async: false" do in jQuery.ajax()?
$.ajax - dataType
encode json using php?
How to get JSON data on ajax call
how to parse json data with jquery / javascript?
when you call $.ajax, function, you define a parameter called successful and you usually give it a function to be executed once the call is successful meaning: the server has been called with the given parameters and a response was received. The response could (or could not) contain additional data passed in the data variable that you would use when calling the successful function.
Here is the tricky part: although the parameter is called successful, in your context, the provided credentials might not be valid, so, in your PHP code, you would notify the ajax call that the login attempt was not accepted, and you might want to pass the information inside the data variable.
The above scenario describes an unsuccessful login attempt, but a successful ajax call. Here is what you need to do in your javascript code to distinguish whether the user should be forwarded to next page or not:
$.ajax({
type: "POST",
url: '/test/login.php',
dataType: 'json',
async: false,
data: person,
success: function (data) {
// your php code should populate the (data) variable
// in this example I used the variable as a string,
// but you could use json notation and have a more
// complex structure (like data.valid = true)
if (data == "valid_credentials") {
window.location.href = 'nextpage.php';
}
else
{
alert('the provided credentials were not accepted.');
}
}
});

AJAX POST DATA NOT WORKING

This is my jQuery-Ajax code:
<script>
$('#sbmt').click( function(){
$.ajax({
type: 'post',
data: $("#ajxfrm").serialize(),
url: "postdata.php",
cache: false,
success: function (data)
{
alert('updated table');
}
});
});
</script>
HTML CODE:
<form id="ajxfrm" method="post" action="">
<label>HIGH : </label> <input type="text" name="hi" id="hi"><br><br>
<label>LOW : </label><input type="text" name="lo" id="lo"><br><br>
<label>OPENING STOCK : </label><input type="text" name="opn" id="opn"><br><br>
<label>CLOSING STOCK : </label><input type="text" name="cls" id="cls">
<input type="submit" value="Submit" id="sbmt">
</form>
AND PHP CODE ON postdata.php file is :
require_once 'config.php';
$hi = $_POST['hi'];
$lo = $_POST['lo'];
$opn = $_POST['opn'];
$cls = $_POST['cls'];
echo $hi;
$postdata = "INSERT INTO htmdem ( high,low,open,close ) VALUES('$hi','$lo','$opn','$cls');";
mysql_query($postdata);
When posting via form without ajax the table is getting updated as it should, but while using AJAX its not. Please suggest what's wrong here. Many Thanks
Try this : Dont forget to set the form action to postdata.php
jQuery(function($) {
$('#ajxfrm').submit( function(e){
$.ajax({
type: 'post',
data: $(this).serialize(),
url: $(this).attr("action")
})
.done(function (data){
alert('updated table');
});
e.preventDefault();
});
});
Modify your html to add action to form:
<form id="ajxfrm" method="post" action="postdata.php">
Try handling form submit event instead:
$('#ajxfrm').submit(function(event){
$.ajax({
type: 'post',
data: $(this).serialize(),
url: $(this).attr("action"),
cache: false,
success: function (data)
{
alert('updated table');
}
});
return false; //to prevent form submission
//or event.preventDefault();
});
BTW, using success callback is deprecated and post requests are not cached so we also don't need cache:false
$('#ajxfrm').submit(function(event){
$.ajax({
type: 'post',
data: $(this).serialize(),
url: $(this).attr("action")
})
.done(function (data){
alert('updated table');
});
return false; //to prevent form submission
//or event.preventDefault();
});
change your input type="submit" to input type="button". that should do the trick I guess.
Assuming you have included the jquery library in your page,
First, run your page with with your firefox/chrome and use their firebug/console to verify that your ajax is actually posting data to your php page.
Second, modify your query execution in your php file, to catch query errors:
mysql_query($postdata) or die(mysql_error());
One of these cases will help you determine your problem
For Firefox: get the Firebug addon from https://getfirebug.com/
After installing it and restarting firefox, press F12. A console will open.
Run your ajax call and check in the console if data are being posted.

Trouble POSTing form with AJAX

edit - the info appears to be posting, but on form_data.php it doesn't seem to be retrieving the posted values
Here's the AJAX
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#submit_boxes").submit(function() { return false; });
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: function(data) {
$('#view_inputs').html(data); //view_inputs contains a PHP generated table with data that is processed from the post. Is this doable or does it have to be javascript?
});
return false;
});
};
</script>
</head>
Here is the form I'm trying to submit
<form action="#" id = "submit_boxes">
<input type= "submit" name="submit_value"/>
<input type="textbox" name="new_input">
</form>
Here is the form_data page that gets the info posted to
<?php
if($_POST['new_input']){
echo "submitted";
$value = $_POST['new_input'];
$add_to_box = new dynamic_box();
array_push($add_to_box->box_values,$value);
print_r($add_to_box->box_values);
}
?>
Your form is submitting because you have errors which prevents the code that stops the form from submiting from running. Specifically dataType: dataType and this.html(data) . Firstly dataType is undefined, if you don't know what to set the data type to then leave it out. Secondly this refers to the form element which has no html method, you probably meant $(this).html(data) although this is unlikely what you wanted, most likely its $(this).serialize() you want. So your code should look like
$('form#submit_boxes').submit(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: success
})
return false;
});
Additionally if you have to debug ajax in a form submit handler the first thing you do is prevent the form from submitting(returning false can only be done at the end) so you can see what errors occurred.
$('form#submit_boxes').submit(function(event) {
event.preventDefault();
...
});
You can use jQuery's .serialize() method to send form data
Some nice links below for you to understand that
jquery form.serialize and other parameters
http://www.tutorialspoint.com/jquery/ajax-serialize.htm
http://api.jquery.com/serialize/
One way to handle it...
Cancel the usual form submit:
$("#submit_boxes").submit(function() { return false; });
Then assign a click handler to your button:
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: this.html(data),
success: success,
dataType: dataType
})
return false;
});

Printing JSON array to screen via ajax to php script

I've been comparing my code to other examples on the web and I still can't find my errors.
When I load the page and click submit, nothing happens on the screen. However, in Firebug I receive the POST 200 OK and the PHP script that should be on screen is spelled out in the POST response tab.
Since Firebug is responding appropriately, I am confused as to what is wrong.
Basic HTML form
<form id="form" action="" method="post">
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
<div id="results"></div>
jQuery creates a JS object. The object is sent through JSON.stringify and JSON.parse. The submit event handler fires off the $.ajax. JSON data is passed to ok.php and it should return the PHP info called in the script, in theory.
var addIt = new Object();
addIt.one = "one";
addIt.two = 2;
addIt.three = addIt.one +" + "+ addIt.two +" = "+ "three";
$jsonAddIt = JSON.stringify(addIt);
$jsonAddIt = JSON.parse($jsonAddIt);
$('#submit').click(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'ok.php',
dataType:'json',
data: ({ json:$jsonAddIt }),
success:function(data) {
$("#results").html(data);
}
});
});
PHP
<?php
$ajaxInfo = $_POST["json"];
if ($ajaxInfo !="")
{
echo "info transfered";
}
else
echo "nothing";
?>
<div id="returned">
<?php print_r($ajaxInfo); ?>
</div>
Setting the dataType to JSON will make jQuery ajax request to parse it automatically to a Javascript object. You have two solutions here. Either change the dataType of the ajax request:
$.ajax({
type:'POST',
url: 'ok.php',
dataType:'text',
data: ({json:$jsonAddIt}),
success:function(data){
$("#results").html(data);
}
});
Or you could use this library to stringify the object:
$.ajax({
type:'POST',
url: 'ok.php',
dataType:'json',
data: ({json:$jsonAddIt}),
success:function(data){
$("#results").html(JSON.stringify(data));
}
});
Hope it helps.
These two lines are not needed, the second one undoes the first one. just remove them both.
$jsonAddIt = JSON.stringify(addIt);
$jsonAddIt = JSON.parse($jsonAddIt);
This line should be giving you [object Object] in your div if the ajax request was successful, else it will do nothing (which is your current outcome).
$("#results").html(data)
Currently your ajax request is actually failing because it is not returning the expected JSON datatype. If you change your dataType to "html" it will work.
$.ajax({
type:'POST',
url: 'ok.php',
dataType:'html',
data: {json:addIt},
success:function(data){
$("#results").html(data);
}
});
Also,
var addIt = new Object();
should be
var addIt = {};
I think the issue is your dataType. By saying json, you're telling jQuery that the content you're expecting back is json. Where php is likely setting the content-type to html in the header. You should be able to remove that and jQuery will automatically figure it out from the header of the response.

AJAX form submission and results

Just started using AJAX today via JQuery and I am getting nowhere. As an example I have set up a job for it to do. Submit a form and then display the results. Obviously I haven't got it right.
The HTML.
<form id="PST_DT" name="PST_DT" method="post">
<input name="product_title_1682" id="product_title_1682" type="hidden" value="PADI Open Water">
<input name="product_title_1683" id="product_title_1683" type="hidden" value="PADI Advanced Open Water">
<input type="submit" name="submit" id="submit" value="Continue" onclick="product_analysis_global(); test();"/>
</form>
<span id="results"></span>
There are actually many more fields all loaded in dynamically. I plan to use ajax to submit to PHP for some simple maths and then return the results but we can worry about that later.
The JQuery
function test() {
//Get the data from all the fields
var alpha = $('#product_title_1682').val();
JQuery.ajax({
type: 'POST',
url: 'http://www.divethegap.com/update/functions/totals.php',
data: 'text=' + alpha,
beforeSend: function () {
$('#results').html('processing');
},
error: function () {
$('#results').html('failure');
},
timeout: 3000,
});
};
and the PHP
<?php
$alpha = $_POST['alpha'];
echo 'Marvellous',$alpha;
?>
That's my attempt and nothing happens. Any ideas?
Marvellous.
First of all, you're passing the $_POST variable as 'text' while your script is looking for $_POST['alpha']. If you update your PHP to $_POST['text'], you should see the proper text.
Also, if your form is going to have lots of inputs and you want to be sure to pass all of them to your AJAX Request, I'd recommend using jQuery's serialize() method.
data: $('#PST_DT').serialize(), // this will build query string based off the <form>
// eg: product_title_1682=PADI+Open+Water&product_title_1683=PADI+Advanced+Open+Water
In your PHP script you'd then need to use $_POST['product_title_1682'] and $_POST['product_title_1683'].
UPDATE Add a success callback to your $.ajax call.
function test() {
// serialize form data
var data= $('#PST_DT').serialize();
// ajax request
$.ajax({
type : 'POST',
url : 'http://www.divethegap.com/update/functions/totals.php',
data : data,
beforeSend : function() {
$('#results').html('processing');
},
error : function() {
$('#results').html('failure');
},
// success callback
success : function (response) {
$('#results').html(response);
},
timeout : 3000,
});
};
In your PHP script you can debug the information sent using:
var_dump($_POST);
In your AJAX request, you are sending the parameter foo.php?text=..., but in the PHP file, you're calling $_POST['alpha'], which looks for foo.php?alpha=....
Change $_POST['alpha'] to $_POST['text'] and see if that works.
There is a simpler method:
$("#PST_DT").submit(function(e){
e.preventDefault();
$.ajax({
data: $(this).serialize(),
type: "POST",
url: 'http://www.divethegap.com/update/functions/totals.php',
success: function(){
....do stuff.
}
});
return false;
});
This will allow you to process the variables like normal.

Categories