AJAX POST DATA NOT WORKING - php

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.

Related

Ajax script writing

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

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

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

Updating database with jQuery AJAX works only one time

I'm trying to update a database by using jQuery. The function works just fine, but only once. I have to refresh the page and clear the cache if I want to update the database again. I'm using MODX Revolution, I'm not sure if that has anything to do with this problem. Here is the code:
<html>
<head>
<script language="javascript" type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$('#paina').submit( function updateTitle() {
var mail = $("#output").val();
$.ajax({
type: "POST",
url: "gettable.php",
data: "mail="+ mail,
cache: false,
success: function(data){
alert(mail);
}
});
return false;
});
});
</script>
<form id="paina" name="test" action="javascript:updateTitle()" method="post">
<input type="text" id="output">
<input type="Submit" value="Update">
</form>
</body>
</html>
PHP:
<?php
$mail=$_POST["mail"];
$mysqli = mysqli_connect("url", "user", "password", "database_name");
mysqli_query($mysqli, "UPDATE modx_site_content SET pagetitle='$mail' WHERE longtitle='jee'");
echo "Updated!";
$mysqli->close();
From the jQuery docs:
Note: Setting cache to false will only work correctly with HEAD and
GET requests
Ugly fix: append a random parameter to the query string:
$.ajax({
type: "POST",
url: "gettable.php",
data: "mail="+ mail + "&timestamp=" + new Date(), // Will append the current date in milliseconds since January 1, 1970 (correct me if I'm wrong).
cache: false,
success: function(data){
alert(mail);
}
});
Try changing the ajax to be to help debug, I have also added an object to data and set a sync to false to ensure the ajax finishes execution before the return
$(document).ready(function(){
$('#paina').submit( function() {
$.ajax({
type: "POST",
url: "gettable.php",
data: {mail: mail},
cache: false,
async: false,
success: function(data){
alert(mail);
},
error function(){
alert("Failed");
}
});
});
});
You don't need the action on your form either as jQuery is handling it
<form id="paina" name="test" action="" method="post">
Thanks for the tips. I found the solution, MODX Revolution uses xPDO Database Connections so I had to change PHP code to this:
$mail=$_POST["mail"];
$dsn = 'mysql:host=localhost;dbname=databasename;port=3306;charset=utf-8';
$xpdo = new xPDO($dsn,'user','password');
$results = $xpdo->query("UPDATE modx_site_content SET pagetitle='$mail' WHERE longtitle='jee'");

Submitting form with jQuery

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.

Categories