jQuery AJAX submitting not working - javascript

I'm having trouble with a jquery ajax submit form. Here's the jquery code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var number = $("#number").val();
var machine_id = $("#machine_id").val();
var dataString = 'number='+ number + '&machine_id=' + machine_id;
$.ajax({
type: "POST",
url: "http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php",
data: dataString,
});
return false;
});
});
</script>
and here is the form code:
<form name="form" method="post" action="">
<input type="hidden" id="machine_id" name="machine_id" value="5">
<input type="text" id="number" name="number"></input>
<input class="btn btn-small btn-success" type="submit" class="submit" id="submit" name="submit" value="submit">Submit</input>
</form>
And the code of updatetextdatabase.php:
<?php
date_default_timezone_set('America/New_York');//set time zone
$con=mysqli_connect('saslaundry.db.10410357.hostedresource.com', 'saslaundry', 'password', 'saslaundry');//establish connection
// Check connection
if (mysqli_connect_errno())//ping database to check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();//error message
}
mysqli_query($con,"INSERT INTO textrequests VALUES('$_GET[number]', '$_GET[machine_id]') ");
return;
?>
But not only is it not submitting the form, the page also reloads, which is sort of what I was trying to avoid by using AJAX. I feel like the problem is that the function is not being called by the submit button, but I can't figure out why.
Thanks!

try this one use e.preventDefault(); prevent your form to submit and then perform your ajax call
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
e.preventDefault();
var number = $("#number").val();
var machine_id = $("#machine_id").val();
var dataString = 'number='+ number + '&machine_id=' + machine_id;
$.ajax({
type: "POST",
url: "http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php",
data: dataString,
success: function (data) {
//do something here when you got the response
}
});
});
});
</script>
event.preventDefault

I made this working fiddle:
HTML:
<form name="form" method="post" action="">
<input type="hidden" id="machine_id" name="machine_id" value="5" />
<input type="text" id="number" name="number" />
<input class="btn btn-small btn-success" type="button" class="submit" id="submit" name="submit" value="submit" />
</form>
Jquery:
$(document).ready(function(){
$("#submit").click(function() {
var number = $("#number").val();
var machine_id = $("#machine_id").val();
var dataString = 'number='+ number + '&machine_id=' + machine_id;
$.ajax({
type: "POST",
url: "http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php",
data: dataString
});
});
});
Network Console:
Request URL:http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php
Request Headersview source
Accept:*/*
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:http://fiddle.jshell.net
Referer:http://fiddle.jshell.net/WJGhr/show/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Form Dataview sourceview URL encoded
number:25
machine_id:5
Here is the fiddle: http://jsfiddle.net/WJGhr/

Related

Ajax submit doesn't work (can't read $_POST in php)

I am trying to submit my form using Ajax. When the button is clicked the hit() function gets called and passes the contents of the textbox back to test.php
$_POST seems to be empty, since I get the alert from ajax (form was submitted) but I don't get to see the echo (echo $_POST['textbox'])
test.php
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];
}
?>
<html>
<body>
<form action="index.php" method="post" align="center" id="form" name="form">
<script type="text/javascript" src="test2.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
</form>
</body>
</div>
</html>
test2.js
function hit() {
var inputText = $("#input").val();
var inputTextString = "textbox=" + inputText;
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
}
There're more of problems here
In test.php
how can you include your js file before you include jquery .. first is first ..
After Tested Yes you can use jquery $() inside a function without getting $ undefined error while you'll run the function after include jquery .. sorry my bad
Scripts should be on the <head></head> or before </body>
while you using just button click why you're using <form>
your code should be something like that
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];
return false;
}
?>
<html>
<head>
</head>
<body>
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
<script type="text/javascript" src="test2.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
</body>
</div>
</html>
On test2.js
function hit() {
var inputText = $("#input").val();
var inputTextString = {textbox : inputText}; // use this
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
}
Note: for me I prefer to use separated php file to use it with ajax .. it'll make it easier for outputs
If you need to use a form .. you can use your form code including my notes above and make your submit button type="submit" and remove onclick="hit()" from it then on your js file you can use
$(document).ready(function(){
$('form').on('submit',function(e){
e.preventDefault(); // to prevent form reload
var inputText = $("#input").val();
var inputTextString = {textbox : inputText}; // use this
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
});
});
you never test if you see the reponse from echo - hence you don't alert the response from php at all.
To see what your php script returns you have to alert (or log, or do something usefull with) the passed in parameter to the success callback:
....
success: function (response) {
alert(response);
console.log(response);
},
....
Anyway you should make sure to not send additional data (like unneeded html in your case) back to ajax, but only the value/json. So in your case an exit; after echo would help.
Also follow #Mohammed-Yousef's instructions for the other issues!!
you will get the desired results in the response.
function hit() {
var inputText = $("#input").val();
$.ajax({
type: 'post',
url: 'test.php',
data: {textbox : inputText},
success: function (res) {
alert(res);
}
});
}
And you need to change in your test.php file.
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];exit;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="test2.js"> </script>
</head>
<body>
<form action="index.php" method="post" align="center" id="form" name="form">
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
</form>
</body>
</div>
</html>

serialized form not sending ajax

I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!

How to post mutliple forms from a webpage

I want to post 2 forms using javscript, but I can't seem to figure it out. Can someone help me?
It seems like I need to submit the first form Async according to this but I don't follow their code: Submit two forms with one button
HTML
<form name="form1" action="https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST" target = "me1">
<input type="hidden" name="oid" value="00Df00000000001" />
</form>
<form name="form2" action="https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST" >
<input type="hidden" name="oid" value="00Df00000000001" />
</form>
<input name="submit" value="Submit Form" onclick="submitForms ()" type="button">
JS
function submitForms(){
document.forms["form1"].submit(); /* should be Async?*/
document.forms["form2"].submit();
}
var str1 = $( "form1" ).serialize();
var str2 = $( "form2" ).serialize();
ajaxReq(url,str1);
ajaxReq(url,str2);
function ajaxReq(url,data){
var request = $.ajax({
url: url,
type: "POST",
data: data,
dataType: "html"
});
request.done(function(html) {
console.log('SUCCESS')
});
request.fail(function( jqXHR, textStatus ) {
console.log("AJAX REQUEST FAILED" + textStatus);
});
}

Ajax - How to submit one by one input value - Codeigniter

Sorry for my english is not so good. And i'm newbie :)
I want to update one-by-one input value with ajax in Codeigniter, but it not work right.. only one save button (one form) work, others form not work .. please help me edit below code
Here's the demo code:
View:
<script>
$(function(){
$(".submit45").click(function(){
dataString = $("#prod_upd").serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
document.getElementById('dd').innerHTML=data;
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" id="prod_upd" method="post" >
<input type="text" name="p_ppx" id="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" id="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="button" name="sub" id="sub" class="submit45" value="Save4" />
<div id="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>
Controller:
function change_ppx3(){
$id_p = $_POST['ids_p'];
$rs = $this->ppx->get_ppx_by_id($id_p);
$ppx_value = $_POST['p_ppx'];
$this->ppx->update_ppx(array("id"=>$id_p),array("ppx_r"=>$ppx_value));
if($_POST['p_ppx']):
echo "done: ";
print_r($_POST['ids_p']);
echo "-";
print_r($_POST['p_ppx']);
return true;
endif;
}
because every form has the same id="prod_upd".
test this
<script>
$(function(){
$(".prod_upd").submit(function(){
var $this = $(this), dataString = $this.serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
$this.find('.dd').html(data);
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" class="prod_upd" method="post" >
<input type="text" name="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="submit" class="submit45" value="Save4" />
<div class="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>

Ajax is giving me an error when I send data

I am trying to submit a form by Ajax but I am unable to . I have multiple forms and I am using (this) to submit the data. I am getting the error From error:0 error.The alert messages are showing me that I have the value.
<script type="text/javascript">
$(document).ready(function() {
$(".submitform").click(function (){
alert ($(this).parent().serialize());
$.ajax({
type: "POST",
url: "reply_business.php",
timeout:5000,
data: $(this).parent().serialize(),
beforeSend: function(xhr){
$('#load').show();
},
success: function(response){
$(this).parent().find('.sentreply').append(response);
$('.sentreply div:last').fadeOut(10).fadeIn(2000);
//uncomment for debugging purposes
//alert(response);
},
error: function(jqXHR) {
alert ('From error:' + jqXHR.status + ' ' +jqXHR.statusText);
},
complete: function(jqXHR, textStatus){
//uncomment for debugging purposes
//alert ('From complete:' + jqXHR.status + ' ' +jqXHR.statusText + ' ' + textStatus);
$('#load').hide();
}
});
});
});
</script>
I am creating the form below by the PHP code
foreach ($array['business_ids'] as $business)
{
?>
<form >
<input type="hidden" name="b_id" value="<?php echo $business ; ?>" />
<input type="hidden" name="c_id" value="<?php echo $sqlr['conversation_id']; ?>" />
<input type="hidden" name="q_id" value="<?php echo $sqlr['query_id']; ?>" />
<input type="hidden" name="u_id" value="<?php echo $sqlr['u_id']; ?>" />
<textarea name="reply">Type the reply here.</textarea>
<input type="submit" class="submitform" value="Submit">
</form>
<?php
}
I do not understand why Ajax isn't able to send the data.
Without seeing the markup or the network traffic, we can only guess. Perhaps $(this).parent() isn't the form?
It's typically safer to attach $(form).submit() than $(button).click() for this reason and because $(button).click() doesn't capture form submit by hitting the enter key.
Edit Here's an example:
<form id="theform">
<input type="text" id="thetext" name="thetext" />
<input type="submit" value="send" />
</form>
<form id="anotherform">
<input type="text" id="anothertext" name="anothertext" />
<input type="submit" value="save 2" />
</form>
<script>
$(document).ready(function () {
$("#theform").submit(function (e) {
var data = {
thetext: $("#thetext").val()
};
$.ajax("/the/server/url", {
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function (r) {
alert("done");
}
});
// Technically you need only one or the other
e.preventDefault();
return false;
});
});
</script>
You seem to have submitted the form after starting the Ajax request - and when the page is unloaded, the request is cancelled. Since your form has no action, the submit will just reload the current page so you might not notice it.
To prevent this, you will need to preventDefault() the catched event. Also, you should not handle just click events on submit-buttons, but rather the submit-event of the <form> itself.

Categories

Resources