Submitting form with jQuery - php

Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.

var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});

$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)

I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});

The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.

Related

Update Mysql records using Ajax/Json isn't working

What I'm trying to do is to edit mysql records using php. I've used Ajax/Json to edit a single record, but the problem is my codes isn't working. I tried to alert the value of input element after I clicked the save button and the alert output is verified. And also I don't get any message in console.
Here's what I got right now. Any help will appreciate.
Index.php
<div class="entry-form1">
<form action="" method="post">
<input type="text" name="id_edit" id="id_edit" class="inputs_edit">
<input type="text" name="approved_edit" id="approved_edit" class="inputs_edit">
<input type="submit" name="save_edit" id="save_edit" value="Save"/>
</form>
</div>
Search.php
$query1 = $mysqli->query(""); // not to include
while($r = $query1->fetch_assoc()){
<td><a href='#' name='".$r['id']."' id='".$r['pr_id']."' class='edits'>Edit</a></td>
}
<script>
$(document).ready(function(){
$(".edits").click(function(){
$(".entry-form1").fadeIn("fast");
//not to include some parts of codes
$.ajax({
type: "POST",
url: "auto-complete.php",
data :edit_post_value,
dataType:'json',
success:function(data){
var requested=data.requested;
var id=data.id;
//send to element ID
$('#id_edit').val(id);
$('#requested_edit').val(requested);
}
});
$("#save_edit").click(function () {
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data))
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});
</script>
Item_edit.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
if(isset($_POST['id_edit'])) {
$id_edit= $_POST['id_edit'];
$requested_edit= $_POST['requested_edit'];
$sql = $mysqli->query("UPDATE pr_list SET requested='$requested_edit' WHERE id='$id_edit'");
if($sql){
echo json_encode(array( "success" => "1"));
}else{
echo json_encode(array("success" => "0"));
}
}
?>
1) First, you're not capturing the click event, because $("# save_edit") is within a function that is not being called. So, you're not even sending the form to the server.
2) Second, the way a form works by default send the data and then reload the page, you must call the preventDefault() function from the event object captured to prevent it, before making the ajax call.
try this:
$(document).ready(function(){
$("#save_edit").click(function (e) {
e.preventDefault(); //prevent a page reload
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "/item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data));
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});

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;
});

Very simple jquery AJAX post issue

I've been trying to find the problem for the last couple of hours, but no solution.
I'm having an issue with the following AJAX post request.
$("#about_button").click(function(e)
{
var about = $("#input_about").val();
$.ajax
({
type: 'POST',
url: location.href,
data: {
'about' : about,
},
success: function(message)
{
},
complete: function(message)
{
alert(about);
}
});
e.preventDefault();
});
Here is the html part of the code;
<textarea id="input_about" name="input_about"></textarea>
<input type="button" id="about_button" class="button" value="Update" />
And finally the PHP part at the beggining of the file;
<?php
require_once("headers.php");
if(isset($POST["about"]))
{
$data= $POST["about"];
$database->query("UPDATE hakkimizda set icerik='$data'");
echo '<script type="text/javascript">alert("dsdsfdsdfsf"); </script>';
}
?>
When I click the submit button, it goes into the complete function and alerts the data, but it looks like the page never receives the post message.
I don't if its related with my issue, but I'm using WAMP on localhost.
Its $_POST["about"] not $POST["about"] also as it stands you are open to sql injections.

How to submit a form with AJAX/JSON?

Currently my AJAX is working like this:
index.php
<a href='one.php' class='ajax'>One</a>
<div id="workspace">workspace</div>
one.php
$arr = array ( "workspace" => "One" );
echo json_encode( $arr );
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').live('click', function(event) {
event.preventDefault();
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
jQuery('#' + id).html(snippets[id]);
}
});
});
});
Above code is working perfectly. When I click link 'One' then one.php is executed and String "One" is loaded into workspace DIV.
Question:
Now I want to submit a form with AJAX. For example I have a form in index.php like this.
<form id='myForm' action='one.php' method='post'>
<input type='text' name='myText'>
<input type='submit' name='myButton' value='Submit'>
</form>
When I submit the form then one.php should print the textbox value in workspace DIV.
$arr = array ( "workspace" => $_POST['myText'] );
echo json_encode( $arr );
How to code js to submit the form with AJAX/JSON.
Thanks
Here is my complete solution:
jQuery('#myForm').live('submit',function(event) {
$.ajax({
url: 'one.php',
type: 'POST',
dataType: 'json',
data: $('#myForm').serialize(),
success: function( data ) {
for(var id in data) {
jQuery('#' + id).html(data[id]);
}
}
});
return false;
});
Submitting the form is easy:
$j('#myForm').submit();
However that will post back the entire page.
A post via an Ajax call is easy too:
$j.ajax({
type: 'POST',
url: 'one.php',
data: {
myText: $j('#myText').val(),
myButton: $j('#myButton').val()
},
success: function(response, textStatus, XMLHttpRequest) {
$j('div.ajax').html(response);
}
});
If you then want to do something with the result you have two options - you can either explicitly set the success function (which I've done above) or you can use the load helper method:
$j('div.ajax').load('one.php', data);
Unfortunately there's one messy bit that you're stuck with: populating that data object with the form variables to post.
However it should be a fairly simple loop.
Have a look at the $.ajaxSubmit function in the jQuery Form Plugin. Should be as simple as
$('#myForm').ajaxSubmit();
You may also want to bind to the form submit event so that all submissions go via AJAX, as the example on the linked page shows.
You can submit the form with jQuery's $.ajax method like this:
$.ajax({
url: 'one.php',
type: 'POST',
data: $('#myForm').serialize(),
success:function(data){
alert(data);
}
});

Categories