I am sending Data to PHP using Ajax.
But blank result receiving.
Client Side Code
<script>
//on click of a button, Below jQuery Ajax code running.
var prodStock= $("#product").html();
$.ajax({
data: prodStock,
url: url,
type: 'POST',
async: false,
success: function(response) {
if (response) {
alert(response);
}
}
});
</script>
<?php
foreach($data['Products'] as $val){
$pro.= $val['product_id'].':'.$val['quantity'].',';
}
?>
<div id='product'>{<?php echo rtrim($pro, ',');?>}</div>
Browser Giving:
<div id="product">{18:1,10:1}</div>
Server Side Code
public function update(){
if ($this->RequestHandler->isAjax()) {
print_r($this->request->data);
}
}
Testing:
If i am sending statically data: {18:1,20:1}, in ajax then working fine. returning Array.
Alternate Solution which i have tried and success.
Client Side Code:
<script>
//on click of a button, Below jQuery Ajax code running.
<?php
foreach($data['Products'] as $val){
$pro.= $val['product_id'].':'.$val['quantity'].',';
}
?>
var prodStock= $("#product").html();
$.ajax({
data: <?php echo "{".rtrim($pro, ',')."}";?>,
url: url,
type: 'POST',
async: false,
success: function(response) {
if (response) {
alert(response);
}
}
});
</script>
Related
So I am working on a project in which I have to pass some form data to a database without reloading the page using Ajax. But the $_POST variable in the PHP file is always empty. I do know that I am actually getting the data from the form since I can print and it looks okay in the javascript code:
$(document).ready(function () {
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
type: 'POST',
data: {name: 'tony'},
dataType: 'json',
success: function (response) {
$('#message').html(response);
}
});
//return false;
});
});
And this is the php code:
<?php
//var_dump($_POST);
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
} else {
echo "error";
}
?>
Use this code instead, you won't need to manually define the parameters to be sent because it will be automatically set by FormData():
$('#form').submit(function(event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
url: "post.php",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
So, turns out I am just stupid.. It was actually working properly after all but I was checking if it works the wrong way. I was actually navigating to the php file by entering the url expecting to see my data printed on the php page. Finally, I checked the response of the POST request and it was working just fine.Thank you for your answers and I apologize for wasting your time.
try this,
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
method: 'POST',
data: {name: 'tony'},
success: function (response) {
$('#message').html(response);
}
});
});
I have a Javascript that calls a PHP script using AJAX get method. If i run the PHP script externally it works fine and creates the file connections.txt. But with JS it is not working
$(document).on("click", "#target2", function(){
var arr = ["one","two","three"];
$.ajax({
type: 'POST',
url: 'hello.php',
data: { name: "saurabh" },
success : function(msg) {
// here is the code that will run on client side after running clear.php on server
// function below reloads current page
alert(msg);
}
});
});
PHP script :
<?php
$fp = fopen('/Users/saurabh/Desktop/connections.txt', 'w');
echo "Saving file";
fwrite($fp, "hello");
//echo $_POST['yourarray']);
fclose($fp);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'hello.php',
data: { name: "saurabh" },
success : function(msg) {
alert(msg);
}
});
});
</script>
I just ran that on my localhost, and it works fine. You must be making some mistake with the onclick function. Do it something like this...
$(document).ready(function(){
$("#someButton").click(function(){
$.ajax({
type: 'POST',
url: 'hello.php',
data: { name: "saurabh" },
success : function(msg) {
alert(msg);
}
});
});
});
I am using ajax for sending to the server that a checkbox is checked and now other inputs fields need to be required:
EDIT: ok i will change the question to be more clarified.
i have this code:
$(document).ready(function() {
$('#button_ajax').click(function() {
var request = jQuery.ajax({
type: 'get',
url: 'http://orenmizrah.git/nir1.php',
data: {'id1': $('#input_text').val()},
async: true,
success: function(){
console.log("sent");
}
});
});
and now i check that i got the info in $_GET['id1'] with php code and if $_GET['id1'] is set, echo something to the browser.
the problem is that $_GET['id1'] is set but there is no output to the browser.
what i should do?
No output is shown in the browser because nothing is done to show it.
$(document).ready(function() {
$('#button_ajax').click(function() {
var request = jQuery.ajax({
type: 'get',
url: 'http://orenmizrah.git/nir1.php',
data: {'id1': $('#input_text').val()},
async: true,
success: function(data){
console.log(data); // outputs the returned data to the console
}
});
});
I have the following code on product.php .. can't seem to echo post variable from ajax post. Alert displays fine. Please help
JQUERY
document.getElementById("LBTest").onchange = function(){
var lbtest = $('#LBTest :selected').val();
$.ajax({
type: "POST",
url: "product.php",
data: {test: lbtest},
success: function()
{
alert("Successful");
}
});
}
PHP
if(isset($_POST['test'])){
$data = $_POST['test'];
echo $data;
}
You need to do something with the data you receive from the ajax call. For example, to put the result into a <div> called resultDiv:
success: function(data)
{
$('#resultDiv').html(data);
alert("Successful");
}
$.ajax({
type: "POST",
url: "product.php",
data: {test: lbtest},
success: function(data)
{
alert("Successful");
}
});
You need to add the data to the success function that is called. You can do this locally or reference another function meant to handle responses coming back from the server.
success: function(data)
{
console.log(data);
alert(data + " was returned from the server");
}
It is a good idea on the server side to json_encode the objects that are being returned and using error codes that can be more appropriately handled on the client.
handleResponse(data) {
var data = $.parseJSON(data);
if(data.code >= 200 || data.code < 300) {
// modify the dom, add data to a model, take over the world with your web app.
}
}
So I am submitting form data on the main page with ajax to a php script that inserts all the data into the database. After finishing though I want to redirect somewhere. So here's my ajax:
$('#form').submit(function() {
if(val.form()) {
var $this = $(this);
$.ajax({
data: $this.serialize(), // get the form data
type: "POST",
url: "scripts/insert.php",
complete: function(response){
var redirect = response.getHeader('Location');
alert(redirect);
}
});
}
return false;
});
And at the end of the php file i have:
header("Location: http://www.google.com", true, 401);
exit();
I use chromephp to debug so when executed the console outputs this:
POST http://www.domain.com/Folder/scripts/insert.php 401 (Authorization Required) jquery.min.js:2
Uncaught TypeError: Object #<Object> has no method 'getHeader' /Folder/:320
So how do I redirect at the end of the script when I'm using ajax? Thanks
Try that:
<?php
ini_set('display_errors', false);
echo ('Location: http://www.google.com');
?>
It worked for me.
JavaScript:
$.ajax({
type: 'POST',
url: "http://localhost/test.php",
data: {name: name },
success: function(output){ window.location = output; }
dataType: dataType
});