I am trying to send a form using Ajax without refreshing the page. It is important that the form gets submitted to the same page, that's why I use url: 'customer-management?form_sent=yes'.
HTML:
<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
<i onclick="$(this).closest(\'form\').submit()" id="' . $get_uncontacted_member->id . '" class="fa fa-phone-square called"></i>
</form>
JS:
$('.called').click(function() {
$.ajax({
type: 'post',
url: 'customer-management?form_sent=yes',
data: $(this).attr('id');
success: function(r) {
alert(r);
}
})
})
PHP:
if (isset($_POST['form_sent']) && $_POST['form_sent'] === 'yes') { return 'That worked!' }
The page gets reloaded and I guess I am doing everything wrong.
You are not passing your data correctly. Since you are doing a POST Request, you should not pass your data as a query string. Instead, pass it thru the data property. Also, add return false; so that the form will not submit.
$.ajax({
type: 'post',
url: 'customer-management',
data: { form_sent: 'yes' },
success: function(r) {
alert(r);
}
});
return false;
You can remove this code:
onclick="$(this).closest(\'form\').submit()"
You have to return false; from your onclick even, or else the browser will continue to submit the form.
onclick="$(this).closest('form').submit(); return false;"
Try this:
<form method="post">
<i id="<?php echo $get_uncontacted_member->id; ?>" class="fa fa-phone-square called"></i>
</form>
<script>
$('.called').click(function()
{
$.ajax({
type : 'post',
url : 'customer-management',
data : {form_sent: 'yes',id:$(this).attr('id')},
success: function(r)
{
alert(r);
}
})
});
</script>
PHP:
<?php
if(isset($_POST['form_sent']) && $_POST['form_sent'] === 'yes')
{
echo 'That worked!';
exit;
}
?>
Related
I am trying to POST simple data using AJAX. My HTML code is
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
My JQuery code is
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== '')
{
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
alert('Success');
}
});
}
});
And my test_chat.php code is
<?php
echo $_POST["sweet"];
echo 'hello';
?>
I want to echo the POST data in a div with the name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.
I know it's happening because the load function is reloading the PHP file but I am looking for a solution so that I can show the POST data on my page.
You could return the data directly from your test_chat.php file after the post request, no need for double request here, return data like :
<?php
echo $_POST["sweet"];
echo 'hello';
?>
Then append it to the div #test_wrap like :
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== ''){
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').html(data).fadeIn("slow");
alert('Success');
}
});
}
});
Hope this helps.
You don't need to echo it with PHP, you can display it directly from the jQuery success callback:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
do ajax request of this way in js file:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
use echo json_encode in php:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>
I don't understand javascript,AJAX very well and need to do this code fast, so if you guys can help, it would be great !
I have a like button on my webpage that allows users to like content:
The html code is as follows:
<form action=\"\" method=\"post\" enctype=\"multipart/form-data\"><button name=\"like$i\">like</button></form>
And the php code:
for ($i = 100; $i >= 0; $i-=1) {
$primid = latest1($i);
$id = $user_data['id'];
if(isset($_POST["like" . $i]) && already_liked($id, $primid)===false) {
add_like($id,$primid);
}
if(isset($_POST["like" . $i]) && already_liked($id, $primid)===true){
echo "you have already liked this art";
}
}
All of the code works fine, but when I click the like button; the page refreshes wich is not ideal ...
I know you can use AJAX to fix this problem; i have looked for answers but they all seem to be for forms with content to insert ect ...
I'm sorry if i seem lazy but i have to finish this fast and don't have time to learn ajax properly for the moment :S
Thanks in advance =)
Observe the following code:
jQuery.ajax({
url: '/some/file.php', //link to your php
method: 'POST', // Method, you can use GET too
data: $('#the-form').serialize() //get form values
}).done(function (response) { //works if response is success
// Do something with the response
}).fail(function () { //works if response is fail
// Whoops; show an error.
});
You can do something like this:
HTML
<form action="" method="post" id="likeForm" onsubmit="return false;">
<input type="submit" name="like<?php echo $id; ?>" value="Like" />
</form>
Sidenote: onsubmit="return false;" is used to prevent uncaught exception: out of memory error in ajax.
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#likeForm').submit(function(){
var value = $(this).children().attr('name');
var param = {value: value};
$.ajax({
type: 'POST',
url: 'yourpage.php', // change this yourpage.php to point to a page where you want to process your ajax request
cache: 'false',
data: param,
beforeSend: function(){
// before send
},
success: function(data){
// success
},
error: function(){
// error
}
});
});
});
</script>
yourpage.php
<?php
for($i = 100; $i >= 0; $i-=1) {
$primid = latest1($i);
$id = $user_data['id'];
if(isset($_POST['value']) && $_POST['value'] == "like" . $i && already_liked($id, $primid)===false) {
add_like($id,$primid);
}
if(isset($_POST['value']) && $_POST['value'] == "like" . $i && already_liked($id, $primid)===true){
echo "you have already liked this art";
}
}
?>
Just to compile the all things that you need:
JavaScript code:
function submitFormData(inputForm) {
jQuery.ajax({
url: '/some/file.php', //link to your php
method: 'POST', // Method, you can use GET too
data: $(inputForm).serialize() //get form values
}).done(function (response) { //works if response is success
// Do something with the response
}).fail(function () { //works if response is fail
// Whoops; show an error.
});
}
Html code:
<form action="" method="post" enctype="multipart/form-data">
<button type="button" onclick="submitFormData(this.form);" name="like$i">like</button>
</form>
Good luck with task implementation.
I''m trying to use ajax to show result login from php. But it's not work. It's show error Undefined index like this.
Notice: Undefined index: userEmail in
C:\xampp\htdocs\controllers\login.controllers.php on line 10
Notice: Undefined index: userPassword in
C:\xampp\htdocs\controllers\login.controllers.php on line 10
Login failed
Here are my source code:
login.views.php
<form id="loginForm" action="/controllers/login.controllers.php" method="post">
<input id ="userEmail" type="text" name="userEmail" placeholder="Email">
<input id ="userPassword" type="password" name="userPassword" placeholder="Password">
<button id ="loginSubmit" type="submit" name="loginSubmit">Login</button>
<div id="msg"></div>
</form>
login.Controller.php
<?php
include("../models/user.models.php");
include("../models/dataBase.models.php");
$dbc = new dataBase();
$connect = $dbc->connect('localhost','root','','how_database','','hide');
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$user = new user();
if ($user->login($connect,$_POST['userEmail'],$_POST['userPassword']) == true){
echo "Login Successful";
}
else {
echo "Login failed";
}
}
$dbc->close($connect);
?>
loginAjax.js
$("#loginSubmit").click(function(){
if ($("#userEmail").val() == "" || $("userPassword").val() == "") {
$("div#msg").html("Please enter your email and password");
}
else {
$.post(
$("#loginForm").attr("action"),
$("#loginForm:input").serializeArray(),
function(data){
$("div#msg").html(data);
}
);
}
$("#loginForm").submit(function(){
return false;
})
});
Update Question:
Now i want to add message "Waiting" when after click submit button, hide it when show result messages. What must i do?. Thanks.
You should need to call serialize() on the form, not serializeArray() on the list of inputs. Try this:
$.post(
$("#loginForm").attr("action"),
$("#loginForm").serialize(),
function(data){
$("div#msg").html(data);
}
);
The difference between the functions is the format the output. serializeArray() returns an object, which may not be in the correct format for your receiving endpoint, and serialize() turns the values of the form in to a querystring.
Try this:
$("#loginSubmit").click(function(){
if ($("#userEmail").val() == "" || $("userPassword").val() == ""){
$("div#msg").html("Please enter your email and password");
}else{
var formData = new FormData($("#loginSubmit")[0]);
$.ajax({
url: $("#loginForm").attr("action"),
type: 'POST',
data: formData,
async: false,
dataType: "json",
success: function (data) {
//here success
},
cache: false,
contentType: false,
processData: false
});
}
$("#loginForm").submit(function(){
return false;
})
});
Use this
$("#loginForm").serialize()
instead of
$("#loginForm:input").serializeArray()
You have to use
$.post(
$("#loginForm").attr("action"),
$("#loginForm:input").serialize(),
function(data){
$("div#msg").html(data);
}
Well, the problem is not new, as I saw (really surf a lot), but still can not find solution for myself.
Description of problem:
Have local Web server - XAMPP;
Firefox 29.0.1
And trying to send POST with $.ajax
function checkUser(){
$.ajax({
type: 'POST',
url: 'ajax/checkUser.php',
data: 'uname='+$("#username").val()+'&pword='+$("#password").val(),
success: function(){
someNewFunc();
},
});
};
This function I'm calling with:
$(document).ready(function(){
$(".button.postfix.login").on("click", function(){
if (($("#username").val() != "") && ($("#password").val() != "")) {
hide(); <-- hide pop ups about empty field
checkUser();
} else {$("#empty").show();} <-- pop ups
});
});
And here code of page with elements:
<input id="username" type="text" placeholder="Username" />
<input id="password" type="password" placeholder="Password" />
<a class="button postfix login" href="#"
onclick="event.preventDefault();">Sign in</a>
I guess that data are going out, but the page checkUser.php doesn't get anything.
What am I doing wrong?
P.S. checkUser.php:
<?php
print_r($_POST);
?>
Result - Array ( )
P.P.S. By the way, if POST change to GET it's working, but need to be POST
$(document).ready(function(){
$(".button.postfix.login").on("click", function() {
var username = $("#username").val();
var password = $("#password").val();
if ((username != "") && (password != "")) {
hide(); <-- hide pop ups about empty field
checkUser(username, password); // Pass the variables here as a parameter
} else {
$("#empty").show();} <-- pop ups
});
// Put the parameters here
function checkUser(username, password) {
$.ajax({
type: 'POST',
url: 'ajax/checkUser.php',
data: { username:username, password:password} //It would be best to put it like that, make it the same name so it wouldn't be confusing
success: function(data){
alert(data);
},
});
};
});
So when you're gonna call it on php
$username = $_POST['username'];
echo $username;
Does your someNewFunc callback fire? Do you see the HTTP AJAX request in the developer console in Firefox?
Try sending your post data as a dictionary to $.ajax:
$.ajax({
type: 'POST',
data: {
uname: $("#username").val(),
pword: $("#password").val()
}
});
I tried many ways to create a simple jquery ajax form but don't know why it is not submitting and/or returning the notification.
Here is my code:
Javascript
...
<script type="text/javascript" src="assets/js/jquery1.11/jquery-1.11.0.min.js"></script>
...
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
HTML
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<a type="submit">Sign up!</a>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
PHP
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
return json_encode($return);
Solved:
There were three problems. And different users solve each of these problems.
In PHP, you must "echo" the return array instead of "return"
At first, you should use a submit button instead of an anchor in the form
In the input, you must set both "id" and "name"
If any of these users want, you can edit or add a new answer with these details, and the points are yours.
You need to do 3 things.
First, wrap your jQuery codes inside $(document).ready() function,
<script type="text/javascript">
$(document).ready(function()
{
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
});
</script>
Second, Add a submit button to your form. Also you are missing the name attribute for the email input field. That causes the error in the php file.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="signup" value="Sign Up!"/>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
Third, echo the results since you are using AJAX to submit the form. return will not have any effects.
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
echo json_encode($return);exit;
I checked and it's working fine.
Hope this helps :)
The problem is in your form.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="submit" value="Submit">
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
The php code needs to echo instead of return.
just like this:
echo json_encode($return);
Also, your form needs a submit button - type="submit" on an <a> tag doesn't trigger the browser's functionality for handling <form>s
Finally, you need to ensure that your special submit handler is loaded at just the right time -- which, if it is included at the bottom of the page, right before the footer, it should be just fine. However, you can ensure this by wrapping it in
$(document).ready(function(){
//[...]
});
doesn't your a type="submit" need to be an input instead? or a button
I am trying to call webmethod in a ajax using jquery in asp.net, but sometimes it works well and sometimes it doesn't.
Here is my ajax code :
$.ajax({
type: "POST",
url: "frmTest.aspx/fncSave",
data: "{}"
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
cache: "false", //True or False
success: function (response)
result = response.d;
if (result != "") {
alert(response);
}
},
Error: function (x, e) {
alert("err");
return false;
}
});
Here My Server Side Code :
<WebMethod()>
Public Shared Function fncSave() As String
Dim sResult As Int16
Try
Dim obj As New ClsCommon()
sResult = obj.Save()
Catch ex As Exception
ex.Message.ToString()
End Try
Return sResult
End Function
$(this) in the "ajax" function is not the form.
So just try:
$('#form_signup').submit(function(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
type: 'POST',
url: 'signup.php',
data: $this.serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
I admit i didn't check the rest of the code, im pretty sure thats the problem.
Of course if the problem still goes, just "f12" and check console and network for server request and headers, make sure all the params are there.
Hope that helped