I am getting the error message $data is undefined when I try to debug my code by using var_dump($data);
This is my java-script code and the paste bin is my PHP code, there was just too much to put it in one post.
https://pastebin.com/EH0WvA30
However I am not sure what to define it as, or where to define it in my PHP code. Any help would be great. Thanks
function getItinerary (){
$.ajax({
url: 'php/itinerary.php',
type: 'POST',
dataType: 'json',
data: {action: 'LOAD'
userId: $userId,
attractionId: $attractionId
}, //Here put two mode keys and values, userId and attractionId like {userId: '<value here required by your server>',attractionId: '<value here required by your server>'}
success: function(data) {
console.log(data);
alert('request successful');
},
error: function () {
alert('Network or Server error');
}
});
}
Due to this if condition
if(!empty($_POST['userId']) && !empty($_POST['attractionId']) && !empty($_POST['action'])) {
}
If you don't send useId and attractionId in your ajax request, the condition will return false.
I think that's the reason for not working
Update your ajax code like this
function getItinerary (){
$.ajax({
url: 'php/itinerary.php',
type: 'POST',
dataType: 'json',
data: {action: 'LOAD'}, //Here put two mode keys and values, userId and attractionId like {userId: '<value here required by your server>',attractionId: '<value here required by your server>'}
success: function(data) {
console.log(data);
alert('request successful');
},
error: function () {
alert('Network or Server error');
}
});
}
Related
Hi I am currently learning php and I am trying to get data from php file using the below script but i am not getting any response
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " ); // not triggering
}
});
my php return stmt
There might be problems with File URL or file access. You can use complete callback to check request for errors like that:
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " );
},
// This method will be fired when request completes
complete: function(xxhr, status) {
alert("Status code: " + status);
}
});
If the status code is not success that means there is something wrong with your request.
You can check more callback options here.
It doesn't matter whether you use return or echo in your PHP file.
The success method must get a call if it's fine. However, if you use
return instead of echo, nothing will append to your request's data.
On the other hand, The PHP response will include in your 'data' variable in the function success.
You need use data in the assync function success
success: function(data) {
alert("Response : " + data);
},
Thanks for your Responses. I got the Solution to my problem. It seems since Ajax is asynchronous... its taking time to receive the resultant echo value from my php file. so I had to synchronize my Jquery using async : False.
$(function(){
$('#formID').on('submit',function(){
const data_set={
name:"Nipu chakraborty",
"phone":"01783837xxx"
}
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});
I'm stuck here when passing or sending multiple parameters on Ajax. It only works when I pass one. Here the Ajax code:
$.ajax({
type: "POST",
url: "dataCartas.php",
data: {valorXY: valorXY,
CentroX: CentroX},
success: function(msg){
// return value stored in msg variable
console.log(valorXY + CentroX)
}
});
And the PHP code:
$valorXY = $_POST['valorXY'];
$CentroX = $_POST['CentroX'];
include "configX.php";
if ($conn){
$sql="EXEC sp_InsertaComID #ComID = '".$valorXY."', #DR =
'".$CentroX."'";
if ($rs=sqlsrv_query($conn,$sql)){
}else{
echo (print_r(sqlsrv_errors(), true));
}
}else{
die(print_r(sqlsrv_errors(), true));
}
Sorry for my bad english :(
You can serialize a form
$.ajax({
type: 'post',
url: 'include/ajax.php',
data: $('#form').serialize(),
success: function (response) {
// do something
},
error: function(jqxhr,textStatus,errorThrown){
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
}
});
you can also use form data https://stackoverflow.com/a/8244082/3063429
I Am trying to send value from ajax to php and retrieve it just to test that everything is work, when i click in a button to test i got error and alert('Failed') Appears , how can i fix it in order to get success? thanks
Ajax :
var a = "test";
$.ajax({
url: "search.php",
dataType: "json",
data: a ,
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
})
PHP :
<?php
$pictures = "img1";
echo json_encode($pictures);
?>
I refined your code slightly and it works.
var a = "test";
$.ajax({
type: 'POST',
url: 'search.php',
data: 'a=' + a,
dataType: 'json',
cache: false,
success: function (result) {
alert('Successful');
},
error: function (result) {
alert('Failed');
}
});
If you're requesting a JSON, use the $.getJSON from jQuery, it's aready parse the JSON into a JSON object for you.
Seems that you're not return an actual JSON from server, maybe this is what is causing the error.
If you're seeing the 'Failed' message probably the problem is a 500 error which is a server error.
Try this code above.
Javascript:
var a = "test";
$.getJSON("search.php", {
a: a
}, function (json) {
console.log(json);
});
PHP:
<?php
$pictures = ["img1"];
echo json_encode($pictures);
The only way to this not work, is if you have a huge mistake on you webserver configuration.
Your ajax is wrong, it should be:
var a = "test";
$.ajax({
type: "POST",
url: "search.php",
dataType: "json",
data: {a:a},
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
});
I have the following Jquery code that sends a ajax request to add-to-cart.php.
var productData = {
"product_id": s_product_id,
"product_opties": s_product_opties,
"product_aantal": s_product_aantal
}
productData = JSON.stringify(productData);
$.ajax({
url: 'inc/add-to-cart.php',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: productData,
type: 'POST',
success: function(response) {
alert(response.d);
},
error: function(e){
console.log(e);
}
});
Add-to-cart.php:
<?php
print $_POST['product_id'];
?>
I am having two problems, the first one is that the $_POST['product_id'] does not exists when i ask for it and secondly when the ajax response returns it goes directly to the error: function and not succes function
The console log says:
[object Object]{readyState: 4, responseText: "<br /> <b>N...", status: 200, statusText: "OK"}
If the status is OK why does it jump to the error: part?
Thanks!
Try with:
...
var productData = {
'product_id': s_product_id,
'product_opties': product_opties,
'product_aantal': product_aantal,
}
$.ajax({
url: 'inc/add-to-cart.php',
dataType: 'json',
data: productData,
type: 'POST',
success: function(response) {
console.log(response.d);
},
error: function(e){
console.log(e);
}
});
...
Omitting the AJAX contentType parameter and the part where you stringify your JSON, that's already ready to be sent to your url, so, isn't needed.
Remove the line
productData = JSON.stringify(productData);
Then do not return HTML <br> ... from add_to_cart.php, you need to return a JSON string created by the PHP function json_encode and NOTHING ELSE.
Like in:
<?php echo json_encode(array('d' => 'value of d'));
First: status Code from the Webserver is 200 cause he deliverd an existing site.
Second: You dont need to stringify the json object by urself
The following script is failing and I have no idea why. Can anyone see anything glaring? I just used and alert to make sure that the userID and the postID were correct and they were so I know the call to the values is correct and I have the processing page in the same directory just to get it to work for now.
$(document).ready(function() {
$('#saveme').click(function() {
$.ajax({
type: "POST",
url: "save_recipe.php",
contentType: "application/json; charset=utf-8",
data: { 'postID': $('#post_id').val(), 'userID': $('#user_id').val() },
dataType: "json",
success: function (msg) {
alert("This recipe has been saved in your profile area!");
},
error: function (request, status, error) {
alert(request.responseText);
},
//alert('PostID: '+ $('#post_id').val() +' UserID: '+$('#user_id').val());
});
});