jquery $.post not working unless debugging - javascript

I have simple form for updating the stock of products, it uses datatables to generate rows for all the items in the database. I can update the stock correctly using the form when I set a break point in the function, but if I remove the break point it stops working.
HTML form:
<form id="updateStock">
<input id="Penguincard" type="text" value="200">
<input type="submit" onclick="updateStock("Penguincard", "Penguin card");" value="Update">
</form>
Javascript:
function updateStock(id, item){
var idS = "#" + id;
var newStock = $(idS).val();
$.post("URL",{item: item, stock: newStock},
function(result){
alert(result);
});
return false;
}
PHP:
<?php
ini_set('display_errors', 1);
// Adds a new item to the database
require('common.php');
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["item"])){
echo 'item is blank';
exit();
}else
{
$item = test_input($_POST["item"]);
// check if item only contains letters and whitespace
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$item))
{
echo 'item reg';
exit();
}
}
if (empty($_POST["stock"])) {
echo 'stock is blank';
exit();
}else
{
$stock = test_input($_POST["stock"]);
// check if stock only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$stock))
{
echo 'stock reg';
exit();
}
}
}else{
//don't run unless post
echo 'Not post';
exit();
}
$stmt = $db->prepare('UPDATE `stock` SET `stock`=:stock WHERE `item`=:item');
// bind the parameters to the insert after sanitizing them
$stmt->bindParam(':item', $item);
$stmt->bindParam(':stock', $stock);
//execute the insert
$status = $stmt->execute();
if( $status ){
echo 'Item added successfully!';
exit();
}
//sanitizing function
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
EDIT: by not working I mean it seems to run the onClick function but doesn't submit the post.
From the answers it seems that debugging was allowing the post to be submitted before the default form action occurred, therefore making it working.

You're never actually suppressing the click functionality of the submit button; you return false; from the updateStock function, but that doesn't actually do anything (the onclick attributes code itself needs to be returning false. As a result the form is being submitted and the AJAX request is cancelled.
The simplest fix would be this:
<input type="submit" onclick="return updateStock('Penguincard', 'Penguin card');" value="Update">
However, it would probably be better to use jQuery to bind the event handler:
$(':submit').on('click', function(e) {
e.preventDefault();
updateStock('Penguincard', 'Penguin card');
});

This line is the issue:
onclick="updateStock("Penguincard", "Penguin card");"
The double quotes inside the attribute are the problem. Convert them to single quotes. This is one reason why people like to use the jQuery delegates to add click events.

Related

Php post form without refresh page

I try to post my form to Mysql without refreshing page. I did these with looiking sources but not working. Could you help me?
<script>
$('#submit').click(function() {
$.ajax({
url: 'submit.php',
type: 'POST',
data: {
message: '*I couldnt find this partwhat should i write*'
}
}
});
});
</script>
<form method="post">
<textarea name="message" rows="3" cols="30">
</textarea><br><br>
<input type="submit" value="Submit">
</form>
Submit.php
<?php
include "connect.php";
if(isset($_POST['message'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
$post = $_POST['message'];
$date = date("y-m-d G:i:s");
$query = $db->prepare("INSERT INTO chat_messages SET senderid = ?, receiverid = ?, message = ?, mod_time = ?");
$insert = $query->execute(array( $a, $b, $post, $date));
}?>
In jQuery, the click event is being triggered on an element that has an id of submit (it is id because it is represented by #)
$('#submit').click(function() {
Your submit button does not have the ID of "submit"
Change the input tag as follows:
<input id="submit" type="submit" value="Submit" />
Another problem, as #Rajan in comments pointed out, you have an extra brace. So, change:
data: {
message: '*I couldnt find this partwhat should i write*'
}
}
to:
data: {
message: '*I couldnt find this partwhat should i write*'
}
Also, I recommend that you show return some kind of message from submit.php page, for example:
echo 'Entry Added';
The above is just an example output to get you going... you really should be doing checks such as: did the entry get inserted without any errors, etc.
Edit
Also note: you are using type as one of the settings. Per the official jQuery documentation of jQuery.ajax(), type is:
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
(i.e. use method instead, if using jQuery version >1.9.0)
Lastly, take a look at the answer provided by #Faisal as well...
You are submitting form data through Ajax query, hence you do not need to include header('Location: ' . $_SERVER['HTTP_REFERER']); in your submit.php file.
<form>
<textarea name="message" rows="3" cols="30"></textarea>
<br>
<input type="submit" value="Submit">
</form>
<script>
$(document).ready( function() {
$("form").on("submit", function(e) {
e.preventDefault(); // Prevent default form submission action
$.post("submit.php", $("form").serialize()); // Post the data
$('textarea[name=message]').val(''); // Clear the textarea
});
});
</script>
Also, are the variables $a and $b defined in submit.php file?
$.post('../submit.php',{message:message}, function(data) {
$('.results').html(data);
});
use a div where you want to display the result
<div class="results"></div>
to finish your submit.php have to send something at the end so try this
<?php
include "connect.php";
if(isset($_POST['message'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
$post = $_POST['message'];
$date = date("y-m-d G:i:s");
$query = $db->prepare("INSERT INTO chat_messages SET senderid = ?, receiverid = ?, message = ?, mod_time = ?");
$insert = $query->execute(array( $a, $b, $post, $date));
}
echo "it works";
?>

php array_push not appending the array after the ajax call

I am using ajax and php and i would like to append my array each an everytime i make an ajax call. But it is not working.
These are my codes:
$('#multiple_upload_form' +count).ajaxForm({
target:'#images_preview'+count,
beforeSubmit:function(e){
console.log("gud to go");
},
success:function(data){
console.log(data);
console.log("succeded");
},
error:function(data){
console.log("failde");
}
}).submit();
PHP this is the pHP side of it.Plase help
<?php
$questionArr = array();
if($_POST['image_form_submit']){
array_push($questionArr,$questionNum );
if(is_array($questionArr)){
foreach($questionArr as $val) {
if ($val == $questionNum){
$response['response']= "exist";
echo json_encode($questionArr);
}else{
$response['response']= "question does not exist";
echo json_encode($response);
}
}
}else{
$response['response']= "not array";
echo json_encode($response);
}
}
?>
And this is my HTML
<form method="post"name="multiple_upload_form"id="multiple_upload_form" enctype="multipart/form-data" action="php_work/test.php">
<input type="hidden" name="image_form_submit" value=""/>
<input type="file" name="images[]" id="images" multiple >
</form>
It may help you:
<?php
$questionNum = 1; // Or from anywhere you are getting data into it
$questionArr = array();
$response['response']= "not array"; // Giving Default value
if($_POST['image_form_submit']){
$questionArr[] = $questionNum;
if(!empty($questionArr)){
foreach($questionArr as $val) {
if ($val == $questionNum){
$response['response'] = "exist";
}else{
$response['response']= "question does not exist";
}
}
}
}
echo json_encode($response);
exit;
?>
First: There is one if statement in the PHP which won't return a value, since there's no else. So if $_POST['image_form_submit'] is false, nothing is echoed.
Second: array_push($questionArr, $questionNum); Where do you defined $questionNum in your PHP script?
Third: in your JS: $('#multiple_upload_form' +count) there you try to refer to an element with an id with a number I guess? I don't see such an element in your HTML. I also don't see in the JS code where you define count.
Long answer short: check both PHP and JS codes for errors.

How to call a PHP function within a page using AJAX

I wrote a php function which does the job perfectly if it is called standalone by PHP page. but I want to integrate this function in a program and want to call it when a button is clicked.
My PHP function is
function adddata($mobile){
// outside of this function, another database is already selected to perform different
//tasks with program's original database, These constants are defined only within this
//this function to communicate another database present at the same host
define ("HOSTNAME","localhost");
define ("USERNAME","root");
define ("PWD","");
define ("DBNAME","budgetbot");
// link to mysql server
if (!mysql_connect(HOSTNAME,USERNAME,PWD)) {
die ("Cannot connect to mysql server" . mysql_error() );
}
// selecting the database
if (!mysql_select_db(DBNAME)) {
die ("Cannot select database" . mysql_error() );
}
//inserting phone number into database
$query = "INSERT INTO `verify_bot` (phone_number) values('".$mobile."')";
if(!mysql_query($query)){
die( mysql_error() );
}
// wait for 2 seconds after adding the data into the database
sleep(2);
$query = "SELECT * FROM `verify_bot` WHERE phone_number = ".$mobile;
$result = mysql_query($query) or die( mysql_error() );
// if more than one records found for the same phone number
if(mysql_num_rows($result) > 1){
while($row = mysql_fetch_assoc($result)){
$data[] = $row['response'];
}
// return an array of names for the same phone numbers
return $data;
}else{
// if only one record found
$row = mysql_fetch_assoc($result);
$response = $row['response'];
return $response;
}
// end of function
}
HTML Code is written as
<form action="self_page_address_here" method="post" accept-charset="utf-8" class="line_item_form" autocomplete="off">
<input type="text" name="mobile_number" value="" placeholder="(000) 000-0000" class="serial_item" size="20" id="serialnumber_1" maxlength="10" />
<button id="verify" class="btn btn-primary">Verify</button>
<button id="cname" class="btn btn-primary"><!-- I want to print return value of the php function here --></button>
</form>
I want to call this function and assign the return value to a javascript variable by ajax/jquery.
My code to do this is...
<script type="text/javascript" language="javascript">
$('#verify').click(function(){
var value = $( ".serial_item" ).val();
//I have some knowledge about php but I am beginner at ajax/jquery so don't know what is happening below. but I got this code by different search but doesn't work
$.ajax({
url : "add_data.php&f="+value,
type : "GET"
success: function(data){
document.getElementById("cname").innerHTML = data;
}
});
});
</script>
I would like to share that the above javascript code is placed outside of documnet.ready(){}
scope
Any help would be much appreciated.
Thanks
Because your <button> elements have no type="button" attribute, they're supposed to submit the form using normal POST request.
You should either use type="button" attribute on your buttons, or prevent default form submission using event.preventDefault():
$('#verify').click(function(event){
event.preventDefault();
var value = $( ".serial_item" ).val();
$.ajax({
// there's a typo, should use '?' instead of '&':
url : "add_data.php?f="+value,
type : "GET",
success: function(data){
$("#cname").html(data);
}
});
});
[EDIT] Then in add_data.php (if you call AJAX to the same page, place this code at the top, so that no HTML is rendered before this):
if(isset($_GET['f'])){
// call your function:
$result = adddata(trim($_GET['f']));
// if returned value is an array, implode it:
echo is_array($result) ? implode(', ', $result) : $result;
// if this is on the same page use exit instead of echo:
// exit(is_array($result) ? implode(', ', $result) : $result);
}
Make sure you escape the value on $query.

PHP script unable to gather filename of calling html page

I'm trying to have the mail.php script identify the page that called the script, and return the user to that page and if the form didn't validate, was empty, etc. When I click on submit, it just 404's.
<?php
/*
This first bit sets the email address that you want the form to be submitted to.
You will need to change this value to a valid email address that you can access.
*/
$webmaster_email = "email#email.com";
/*
This next bit loads the form field data into variables.
If you add a form field, you will need to add it here.
*/
$email_address = $_REQUEST['email'];
$comments = $_REQUEST['comment'];
$fname = $_REQUEST['first-name'];
$lname = $_REQUEST['last-name'];
$filename = debug_backtrace();
$page = $filename[0]['file'];
/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC list.
*/
function isInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str)) {
return true;
}
else {
return false;
}
}
// If the user tries to access this script directly, redirect them to the feedback form,
if (!isset($_REQUEST['email_address'])) {
header( "Location: $page" );
}
// If the form fields are empty, redirect to the error page.
elseif (empty($email_address) || empty($comments) || empty($fname)) {
echo "<script type=\"text/javascript\">window.alert('Please fill in the required fields.');
window.location.href = $page;</script>";
exit;
}
// If email injection is detected, redirect to the error page.
elseif (isInjected($email_address)){
echo "<script type=\"text/javascript\">window.alert('Please, Try Again.');
window.location.href = $page;</script>";
exit;
}
// If we passed all previous tests, send the email then redirect to the thank you page.
else {
mail("$webmaster_email", "Feedback Form Results", $comments, "From: $email_address");
echo "<script type=\"text/javascript\">window.alert('Thank You for contacting us!');
window.location.href = $page;</script>";
exit;
}
?>
No need for debug_backtrace(). To get the referring page, you could replace this:
$filename = debug_backtrace();
$page = $filename[0]['file'];
With this:
$page = $_SERVER['HTTP_REFERER'];
However, $_SERVER['HTTP_REFERER'] is unreliable according to the PHP docs:
This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
So another solution is to add an additional field in the referring form and retrieve it in the PHP script e.g.
<input name="referrer" type="hidden" value="<?php echo $_SERVER['PHP_SELF'];?>"/>
Then:
$page = $_REQUEST['referrer'];

There is no alert when submitting a form using ajaxForm plugin

How can I have an alert that the form has been submitted successfully? I have already tried to look at the page of the plugin still come up empty handed.
This is the code I have tried so far maybe there is something wrong with my syntax:
<script type="text/javascript">
$(document).ready(function(){
$('#f1').ajaxForm({
success: function(){
alert("Form successfully submitted");
}
});
});
</script>
The code above works and successfully inserted all the data in the forms but the alert that suppose to appear after successfully submitted the form is missing for some reason.
This is the script that the form uses when submitting:
<?php
$title=$_REQUEST['articletitle'];
$articlemore=$_REQUEST['editor1'];
include "connection.php";
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0)
{
$type=$_FILES['image']['type'];
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO blog(articletitle, articleimage, articlemore) VALUES ('$title', '$data', '$articlemore')";
$results = mysqli_query($link, $query);
if(!$results)
{
echo "Saving Post Failed";
}
else
{
echo "You have a new Post!";
}
}//end if that checks if there is an image
else
{
echo "No image selected/uploaded";
}
// Close our MySQL Link
mysqli_close($link);
?>
Here is the Syntax
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
I hope this will help you
Change this:
$('#f1').ajaxForm({
to
$('#f1').ajaxForm(function(){

Categories

Resources