i have this simple code:
var addUser = "simply";
$.ajax({
type: 'POST',
url: 'userControl.php',
data: {addUser: addUser},
success: function(response){
alert("success");
}
});
this is the page that i POST to: userControl.php, the if statement not entering so i didnt post? but i got alert message "success".
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){ //if page was requested with POST
echo $_POST['addUser'];
}
?>
I got the alert message "success", but the data is not POST to the other page.
Im also try out to write 'simply' with one apostrophe. in another page in the same project i have a same Ajax and its working, so why this one not working? any ideas? i need to do it only with ajax, submit with form will not help me.
thanks
Pass data this way data: 'addUser=' + addUser
see below code
var addUser = "simply";
$.ajax({
type: 'POST',
url: 'userControl.php',
data: 'addUser=' + addUser,
success: function(response){
alert("success");
}
});
and you should remove window.location because it is possible before your ajax call completes page will redirect
Related
I am new to javascript and ajax, I want to call php file which deletes the selected row from Mysql database in a javascript file so I tried to explore the answers I found here concerning this question but I couldn't resolve it, here is the php file called delete-consultation.php:
<?php
global $db;
$idconsult=$_POST['del_id'];
$q = $db->prepare(
'DELETE FROM consultation
WHERE id_consultation = :idc');
$q->bindValue(':idc', (int)$idconsult , PDO::PARAM_INT);
$q->execute();
And here is how I tried to call it using ajax:
$.ajax({
url: "delete-consultation.php",
type: "POST",
cache: false,
data:{
del_id: rows[0]
},
success: function(){
console.log("true");
}
});
I am getting 200 ok as a response but always without the id paraleter and the delete operation is not being executed, am I missing anything? Any advice could help, thanks
I solved the issue by editing the ajax code like this:
$.ajax({
url: "delete-consultation.html",
type: "POST",
cache: false,
datas:{
del_id: rows[0]
},
success: function(){
console.log("true");
},
error: function(){
console.log("false");
}
});
and the php code was correct actually what was wrong is the word 'data' changed to be 'datas':
Posting from javascript ajax (which according to alerts it hits correctly and succeeds at) I cannot get the post from my PHP code.
<script>
function SavePlot() {
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
success:function() {
alert("gets here");
}
});
}
</script>
So above it reaches the gets here alert, so it should be posting, however it isnt caught by the below php:
if(isset($_POST['action']) && $_POST['action'] == 'SavePlot') {
echo '<script>alert("Doesnt get here")</script>';
}
I've tried many other answers but couldn't seem to succeed.
First of all, whatever you echo in your php script won't show up automatically in your current HTML DOM.
However, you can retrieve what you've echo-ed in the PHP in your AJAX call:
success: function(response){
console.log(response);
alert("gets here");
}
In your console, you should see:
<script>alert("Doesnt get here")</script>
Try specifying dataType as HTML in your ajax request.
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
dataType : 'HTML',
success:function() {
alert("gets here");
}
});
I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.
i'm very new in PHP and please don't mark this question as duplicate, because I've searched and found many solutions on stackoverflow as well as other sites, here is the code in my login.php what I'm trying to do is pass some data to controller.php:
window.onload = function(){
$('#btnLogin').click(function() {
var val1 = $('#txtusername').val();
var val2 = $('#txtpassword').val();
var val3 = "login";
$.ajax({
type: 'POST',
url: 'controller.php',
data: { action: val3, username: val1, password: val2 },
success: function(response) {
alert(response);
}
});
});
}
It is working well if I don't want to navigate to another page "index.php" because in controller.php I've received all data what passed from login.php, but the header("Location: index.php") is not working.Bellow is my controller.php:
<?php
header("Location: index.php");
exit();
?>
I've tried some solutions like: "delete blank spaces",add "error_reporting(E_ALL)" and "ini_set('display_errors', 'On') " and "ob_start()" to the top of the controller.php file, but nothing better happen.
You can't do that via ajax request. If you want to navigate to index.php after you finish processing data via controller.php use jquery redirection inside your success response.
success: function(response) {
window.location.replace("index.php");
}
You are doing your redirect in ajax request. This will not redirect your page, it will only redirect the ajax request. Instead return some json response and check this response in the ajax callback and then redirect the user using javascript.
I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});