Ajax JQuery success function not working - javascript

I'm not sure what has gone wrong, but for some reason the success function in Ajax isn't calling the function. I'm asking it to call after the PHP is completed.
For the PHP I have $test = 'Hi'; echo json_encode($test);
Here is my code for the main page:
<?php
session_start();
if(!isset($_SESSION["b2_in"])){
header("Location: b2.php");
}
?>
<script>
$(document).ready(function(){
$("form input:submit").click(function() {
$.ajax({
type: "POST",
url: 'b2_send.php',
data: $('form').serialize(),
dataType: 'json',
//beforeSend: function(){ $("#send").val('Sending...');},
success: function(data) {
TestFunction();
},
statusCode: {
403: function(e) {
$("say").highlight();
$("#message").html(e.responseText);
}
}
});
return false;
});
});
function TestFunction(){
$("#message").val("");
}
</script>
<say>
<form>
<input type="text" name="message" class="Message" id="message"/>
<input type="submit" name="send" value='Say' id="send"/>
<span id="message" style="font-weight:bold;color:red;"></span>
</form>
</say>

Try this
span is a block element of DOM and hence to set data to it, you need to use $(id).html(data); and not val()
Also you should have different id for each elemnt in the dom, it always pick the first id that it gets in the dom, and in your case it is
<input type="text" name="message" class="Message" id="message"/> so it will change the value of this element
<script>
$(document).ready(function(){
$("form input:submit").click(function() {
$.ajax({
type: "POST",
url: 'b2_send.php',
data: $('form').serialize(),
dataType: 'json',
//beforeSend: function(){ $("#send").val('Sending...');},
success: function(data) {
TestFunction();
},
statusCode: {
403: function(e) {
$("say").highlight();
$("#message").html(e.responseText);
}
}
});
return false;
});
});
function TestFunction(){
$("#message").html("");
}
</script>

Related

jQuery Ajax Submit Post not getting success message back

The code works on until I reach the action.php where I post my input. The issue is that the Post never reaches the action.php and all I get is a blank variable.
using: https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('name');
$.ajax({
type: 'post',
url: 'action.php',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});
return false;
}
</script>
<form onsubmit="return submitdata();">
<input type="text" name="name">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
action.php:
<?php
$name=$_POST['name'];
echo "Response: ".$name;
?>
EDIT:
Fixed it by adding:
var name=document.getElementById('name').value;
and
input type="text" id="name" instead of name="name"
Your "name" is DOM object. To get value use:
var name=document.getElementById('name').value;
You now submit not a string, but Object and this may be the reason why it fails.
Try to add the dataType on your ajax request
make it 'text'
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});

How can I execute a PHP function via ajax?

How do I execute a PHP function using ajax? I have multiple functions on my script page but I want to call a single function.
<?php
function one(){return 1;}
function two(){return 2;}
?>
$("#form").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "process.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(response){
alert(response);
}
});
}));
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form action="" method="POST" id="form">
<input type="text" name="text" id="text" />
<button type="submit" id="submit">Upload</button>
</form>
Use Get param "action"
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "process.php?action=one",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(response) {
alert(response);
}
});
}));
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form action="" method="POST" id="form">
<input type="text" name="text" id="text" />
<button type="submit" id="submit">Upload</button>
</form>
Then in your process.php file, just catch the "action"
function one(){
return 1;
}
function two(){
return 2;
}
if ( isset($_GET['key']) && !empty(isset($_GET['key'])) ) {
$action = $_GET['key'];
switch( $action ) {
case "one":{
return 1; // or call here one();
}break;
case "two":{
return 2; // or call here two();
}break;
default: {
// do not forget to return default data, if you need it...
}
}
}
You can call a specific function of your PHP code via AJAX by following few changes in your AJAX call and PHP code.
Eg:
AJAX:
$.ajax({
url: "yourphpfile.php",
data: "function=one", // or function=two if you want the other to be called
/* other params as needed */
});
Then in yourphpfile.php code,
<?php
function one(){return 1;}
function two(){return 2;}
if(isset($_GET['function'])) {
if($_GET['function'] == 'one') {
function one() // call function one
} elseif($_GET['function'] == 'two') {
//function two() // call function two
}
}
?>

Inserting into Mysql form php with Ajax without reload page

I have this jQuery AJAX code that into Mysql form php. It works without reloading the page. The problem is that it When the user enters something into the form, then clicks submit, I would like to use php and ajax (with jquery). But it do not print the string in alert() . Can someone please show me how this can be achieved?
HTML :
<form id="students" method="post">
<div class="row">
<input name="a[]" value="" type="text" >
<input name="b[]" value="" type="text" >
</div>
<div class="row">
<input name="a[]" value="" type="text" >
<input name="b[]" value="" type="text" >
</div>
<input type="submit" value="submit" id="submitbutton" class="insert"/>
</form>
<script type="text/javascript">
$('#students').submit(function(){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
alert('form has been posted successfully');
}
});
});
</script>
and ajax_insert.php :
$a1=$_POST['a'];
$b1=$_POST['b'];
//$query_values = array();
$index=0;
foreach($a1 as $s){
$sql = "INSERT INTO test_data(a,b) VALUES('$s','".$b1[$index]."')";
$result = mysql_query($sql);
if($result)
{
echo "1";
}
$index++;
}
$('#students').submit(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
alert('form has been posted successfully');
}
});
check official document here and learn how to use event.preventDefault();
You probably have to event.preventDefault(); in the submit event callback :
$('#students').submit(function(){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
alert('form has been posted successfully');
}
});
});
You need return valid json when use dataType: "json" in $.ajax call
Or you can use dataType: "html" without rewriting php code
Update (examples of code, that should work):
in HTML:
<script type="text/javascript">
$('#students').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
if(data.result == 1) {
alert('form has been posted successfully');
} else {
alert(data.error);
}
}
});
});
</script>
ajax_insert.php
$a1=$_POST['a'];
$b1=$_POST['b'];
//$query_values = array();
$index=0;
$errors = array();
foreach($a1 as $s){
$sql = "INSERT INTO test_data(a,b) VALUES('$s','".$b1[$index]."')";
$result = mysql_query($sql);
if(!$result)
{
$errors[] = "\"$sql\"";
}
$index++;
}
if(!empty($errors)) {
echo json_encode(array('result'=>0,'error'=>"Error executing following queries: \n".implode("\n", $errors)));
} else {
echo json_encode(array('result'=>1));
}

jquery $.ajax is not working. form post

I want use jquery to sent form data to server,
and I follow this page↓
how do i submit a form using get method in jquery.
But is not working, has no any window alert.
I don't know why....
I already import the jquery script in head(version 1.11.3).
<script src="./static/jquery-1.11.3.js" type="text/javascript"></script>
this is my script.
<script>
function test(){
document.getElementById("form_test").submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( response ) {
alert( response );
},
error:function(){
alert("error");
}
});
return false;
});
}
</script>
this is my form code.
<form id="form_test" class="appnitro" method="post" action="">
<div class="form_description">
<p>test.</p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="info">info</label>
<div>
<input id="info" name="info" class="setInfo" type="text" maxlength="16" value=""/>
<label id="infoMsg" class="Message"></label><br/>
</div>
</li>
<li class="buttons">
<button type="button" class="mbutton" onclick="test()">submit</button>
</li>
</ul>
</form>
Remove the submit handler from test()
document.getElementById("form_test").submit(function () {
This is not required as the function test is being called when user clicks on the button.
function test() {
var $form = $('#form_test');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
}
I would also suggest you to use jQuery on() to bind event
$('#form_test').on('submit', function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
});
You need to have a form submit event handler registered in the dom ready handler
$(function () {
$("#form_test").submit(function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
});
})
In your code, you are calling the test method on click of the button, which calls the form elements submit function with a callback
As you used inline js in submit button, no need for submit event handle for this. See code below :
<script>
function test(){
var myForm = document.getElementById("form_test");
$.ajax({
url : $(myForm).attr('action'),
type : $(myForm).attr('method'),
data : $(myForm).serialize(),
success : function( response ) {
alert( response );
},
error:function(){
alert("error");
}
});
return false;
}

javascript button ajax and php

I have a small question, which I guess in my opinion will sound stupid. I have actually this code
<script type="text/javascript">
$(document).ready(function(){
var email_value = prompt('Please enter your email address');
if(email_value !== null){
//post the field with ajax
$.ajax({
url: '="/new/cfolder.php',
type: 'POST',
dataType: 'text',
data: {data : email_value},
success: function(response){
//do anything with the response
console.log(response);
}
});
}
});
</script>
I would like to link it to my button which does this
<form action="/new/cfolder.php" method="post">
</font><input type="submit" value="Create Vdisk" class="myButton6" onClick="function()">
<br></form>
Is it actually possible to do this? thank you for any answer.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.myButton6', function(){
var email_value = prompt('Please enter your email address');
//post the field with ajax
if(email_value.length > 0){
$.ajax({
url: '/new/cfolder.php',
type: 'POST',
dataType: 'text',
data: {data : email_value},
success: function(response){
alert(response);
}
});
}
)};
});
</script>
try that way
// this is the id of the form
$("#idForm").submit(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: '="/new/cfolder.php',
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
give your form an id
<form id="idForm" action="/Same/path/as/your/ajax/" method="post">
</font><input type="submit" value="Create Vdisk" class="myButton6" onClick="function()">
<br></form>
Yes of course you can do this . Like this code and you will have to include jquery1.9.0.js or above.
<script type="text/javascript">
$(document).ready(function(){
$("#myButton6").click(fuction(){
var email_value = prompt('Please enter your email address');
if(email_value !== null){
//post the field with ajax
$.ajax({
url: '/new/cfolder.php',
type: 'POST',
dataType: 'text',
data: {data : email_value},
success: function(response){
//do anything with the response
console.log(response);
}
});
}
});
});
</script>
I would like to link it to my button which does this
</font><input type="submit" value="Create Vdisk" class="myButton6" id="myButton6">
<br>

Categories

Resources