Passing data through ajax - javascript

I was following a tutorial to pass text to search through ajax, and it works good. Now I want to pass also checkboxes values. Can someone point me to the right direction? Right now I have:
function search(){
var term=$("#search").val();
if(term!=""){
$("#result").html("<img src='/img/spin.gif'/ style='margin-top: 30px;'>");
$.ajax({
type:"post",
url:"file.php",
data:"q="+encodeURIComponent(term), /* encodeURI is used to escape things such as plus sign */
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
}
So, basically I figure the text is sent through the post variable "q". Let's say I have an array of checkboxes, how can I add that to the same post request?

you could use jQuery's serialize.
$('#form').submit(function(e) {
var data = $('#form').serialize();
$.post('form.php',data, function(status) {
if(status == 'success') {
// success
} else {
// error
}
});
e.preventDefault();
});
form.php
<?php
$search = $_POST['search'];
etc...

$.ajax({
type:"post",
url:"file.php",
data: {
q: encodeURIComponent(term), /* encodeURI is used to escape things such as plus sign */
checkboxes: $('input[type=checkbox]').serialize()
}
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});

It will be simpler for you, if you try to serialize your data.
You didn't write how your html looks like, so let's say you have a form like this:
<form id="form">
Search text: <input type="text" name="data[text]"/>
<input type="checkbox" name="data[option]" /> Option 1
<input type="submit" value="Search"/>
</form>
To send this form with ajax request, all you have to do is to serialize your form
$('#form input[type="submit"]').click(function(e) {
e.preventDefault();
$.post("file.php", $("#form").serialize(), function(){
console.log('success');
});
});
Then in your php script you can retrieve data from $_POST variable, for example $_POST['data']['text']

Related

assign php output (ajax) to javascript variable

This is my first time using javascript please be respectful. I have a form which is submitting data via ajax. Everything works as intended, however I'm trying to assign what recd.php is echoing to recresponse so the correct error code is displayed in an alert. Any help or examples would be appreciated.
Form:
<form action="recd.php" method="post" id="GAMEAPPID">
<input type="text" name="GAMEAPPID" id="GAMEAPPID" />
<input type="submit">
</form>
Javascript:
<script>
$(function(){
$("#GAMEAPPID").on("submit", function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr("method"), // <-- get method of form
url: $(this).attr("action"), // <-- get action of form
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
$("#result").html("");
},
success: function(data){
$("#result").html(data);
if(recresponse === "0") {
alert("Incomplete.");
}
if(recresponse === "1") {
alert("Duplicate.");
}
if(recresponse === "2") {
alert("Failed");
}
if(recresponse === "3") {
alert("Thanks");
}
document.getElementById("GAMEAPPID").reset();
refreshMyDiv();
}
});
});
});
</script>
I try to answer. in your "recd.php", you should assign the recresponse to a element like <input type="hidden" id="myRS" value="<?= $myRS ?>" />
and then you can access the element in your javascript.

AJAX to PHP without page refresh

I'm having some trouble getting my form to submit data to my PHP file.
Without the AJAX script that I have, the form takes the user through to 'xxx.php' and submits the data on the database, however when I include this script, it prevents the page from refreshing, displays the success message, and fades in 'myDiv' but then no data appears in the database.
Any pointers in the right direction would be very much appreciated. Pulling my hair out over this one.
HTML
<form action='xxx.php' id='myForm' method='post'>
<p>Your content</p>
<input type='text' name='content' id='content'/>
<input type='submit' id='subbutton' name='subbutton' value='Submit' />
</form>
<div id='message'></div>
JavaScript
<script>
$(document).ready(function(){
$("#subbutton").click(function(e){
e.preventDefault();
var content = $("#content").attr('value');
$.ajax({
type: "POST",
url: "xxx.php",
data: "content="+content,
success: function(html){
$(".myDiv").fadeTo(500, 1);
},
beforeSend:function(){
$("#message").html("<span style='color:green ! important'>Sending request.</br></br>");
}
});
});
});
</script>
A couple of small changes should get you up and running. First, get the value of the input with .val():
var content = $("#content").val();
You mention that you're checking to see if the submit button isset() but you never send its value to the PHP function. To do that you also need to get its value:
var submit = $('#subbutton').val();
Then, in your AJAX function specify the data correctly:
$.ajax({
type: "POST",
url: "xxx.php",
data: {content:content, subbutton: submit}
...
quotes are not needed on the data attribute names.
On the PHP side you then check for the submit button like this -
if('submit' == $_POST['subbutton']) {
// remainder of your code here
Content will be available in $_POST['content'].
Change the data atribute to
data:{
content:$("#content").val()
}
Also add the atribute error to the ajax with
error:function(e){
console.log(e);
}
And try returning a var dump to $_POST in your php file.
And the most important add to the ajax the dataType atribute according to what You send :
dataType: "text" //text if You try with the var dump o json , whatever.
Another solution would be like :
$.ajax({
type: "POST",
url: "xxxwebpage..ifyouknowhatimean",
data: $("#idForm").serialize(), // serializes the form's elements.
dataType:"text" or "json" // According to what you return in php
success: function(data)
{
console.log(data); // show response from the php script.
}
});
Set the data type like this in your Ajax request: data: { content: content }
I think it isnt a correct JSON format.

Post variables to php file and load result on same page with ajax

I have tried searching quite a bit but can't seem to make anything work.
I am trying to make a form that sends info to a PHP file and displays the output of the PHP file on the same page.
What I have so far:
HTML:
<html>
<form id="form">
<input id="info" type="text" />
<input id="submit" type="submit" value="Check" />
</form>
<div id="result"></div>
</html>
JS:
<script type="text/javascript">
var info= $('#info').val();
var dataString = "info="+info;
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
});
</script>
PHP:
<?php
$url = '/api.php?&info='.$_POST['info'];
$reply = file_get_contents($url);
echo $reply;
?>
When I set the form action to api.php, I get the result I am looking for. Basically what I want is to see the same thing in the "result" div as I would see when the api.php is loaded.
I cannot get any solutions to work.
Your click event is not stopping the actual transaction of the page request to the server. To do so, simply add "return false;" to the end of your click function:
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
return false;
});
Additionally, you should update the type="submit" from the submit button to type="button" or (but not both) change .click( to .submit(
Thanks everyone for your help, I have it working now.
I was doing a few things wrong:
I was using single quotes in my php file for the URL and also for the $_POST[''] variables.
I needed to add return false; as Steve pointed out.
I did not have a "name" for the input elements, only an ID.
I think Your code evaluate dataString before it is filled with anything. Try to put this into function of $.ajax. The code below.
/* ... */
$('#submit').click(function (){
$.ajax({
var info= $('#info').val();
var dataString = "info="+info;
/* ... */

passing values from javascript to php

HTML CODE
<form action="phpfile.php" method="post">
<input type="button" id="id1">
<input type="button" id="id2">
<input type="submit">
</form>
<div id="result"></div>
JAVASCRIPT CODE
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
});
Can you give me some tips on how I can send the qty1, qty2 and totalqty to my php file, after I click the submit button. Before I send it to the php file, I need to check first if the button is already clicked. If not, no qty will be send to the phpfile. I need to send the exact number of qty based on how many times you clicked the button.
The easiest solution would be to add qty as <input type="hidden" id="qty1" name="qty1" /> to your form. They will be invisible as your variables, and will be sent to the server as form fields. To access their values from Javascript, use $("#qty1").value()
You're looking for something called AJAX.
This is easy to implement using the jQuery library, but it's also available using regular JavaScript.
If you choose to use the jQuery implementation then your can look at the documentation.
Here's a basic example:
$.ajax({
type : 'post',
url : 'target.php',
dataType : 'json',
data : {
'foo' : 10
}
}).done(function()
{
$(this).addClass("done");
});
You then use the back-end to handle the response, let's for example assume that you send an object of parameters whera one key is named foo and the value is 10, then you could fetch it like this (if the code is PHP):
$foo = isset($_POST['foo']) ? $_POST['foo'] : "";
Using the ternary operator
try using jquery $.ajax or $.post function:
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
get_values(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
get_values(qty2);
});
function get_values(qty_val) {
$.post(
'get_values.php', // url of your php who will receive the values
{ post_variable_name: qty_val }, // your post variables here
function(data) {
// call back function
$("#result").html(data); // see what does your get_value.php echoes via html
console.log(data); // see it via console in inspect element
}
);
}
and in your php that will recieve the values, just retrieve using $_POST:
<?php
$qty_val = '';
if(isset($_POST['post_variable_name'])) {
$qty_val = $_POST['post_variable_name'];
echo $qty_val;
}
?>
HTML
<form>
<input name="id1" type="button" id="id1" />
<input name="id2" type="button" id="id2" />
<input type="submit" />
</form>
<div id="status"></div>
JS
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
});
$( "form" ).submit(function( event ) {
// prevent the default event
event.preventDefault();
// check first if the totalqty. You can add more checks here
if ( totalqty === 0 ) {
// usually show some kind of error message here
alert('No quantity selected!');
// this prevents the form from submitting
return false;
} else {
$.ajax({
type: 'post',
url: 'phpfile.php',
dataType: 'json',
data: {
quantity1: qty1,
quantity2: qty2,
totalQuantity: totalqty
}
}).done(function(data) {
console.log(data);
alert( "success" );
$('#status').html("Successfully saved!");
}).fail(function() {
console.log(data);
alert( "error" );
$('#status').html("Successfully saved!");
});
}
});
PHP
$qty1 = isset($_POST['quantity1']) ? $_POST['quantity1'] : "";
$qty2 = isset($_POST['quantity2']) ? $_POST['quantity2'] : "";
$total = isset($_POST['totalQuantity']) ? $_POST['totalQuantity'] : "";
Sorry, i can't test it, but it should work
For more detailed you could have a look to the jQuery Learning Center - Ajax where you can find useful examples to work with ajax and forms.

Is there a way in JavaScript to retrieve the form data that *would* be sent with a form without submitting it?

If I have an HTML form, let’s say...
<form id='myform'>
<input type='hidden' name='x' value='y'>
<input type='text' name='something' value='Type something in here.'>
<input type='submit' value='Submit'>
</form>
... and then I use jQuery to respond to the form submission event, e.g.
$('#myform').submit(function() {
...
return false;
});
Now suppose I want to submit the form as an AJAX call instead of actually submitting it the “traditional” way (as a new page). Is there an easy way to get a JS object containing the data that would be sent, which I can pass into $.post()? So in the above example it would look something like...
{
x: 'y',
something: 'Type something in here.'
}
or do I have to bake my own?
See the serialize() method.
$('#myform').submit(function() {
jQuery.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function () {
//
}
});
return false;
});
As you're already using jQuery, use jQuery.serialize().
$('#myform').submit(function() {
var $form = $(this);
var data = $form.serialize();
// ...
});

Categories

Resources