Send multiple parameters to PHP (Ajax) - javascript

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

Related

How to define a variable in PHP

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');
}
});
}

php sending values to ajax faild error

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');
}
});

Getting multimple results from Ajax post

Maybe this is a duplicate but I can not understand why mo code does not work. I am trying to get multiple results via Ajax/php.
This is from my php file:
$result11 = 'test1'
$result22 = 'test2';
echo json_encode(array("data1" => $result11, "data2" => $result22));
Ajax call:
$(document.body).on('submit','#sendmessage',function() {
$.ajax({
type: "POST",
url: "/send.php",
data: {par:par,kid:kid,ha:ha,sform:sform,editors:editors},
cache: false,
dataType:'json',
success: function(datax) {
alert(datax.data1);
}
});
return false;
});
Problem:
When I submit a form, the page refreshes instead of sending ajax request.
At the same time this works but I can't get multiple results from Php file:
$(document.body).on('submit','#sendmessagex',function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "/send.php",
data:str,
success: function(data) {
alert(data);
}
});
return false;
});
Add a preventDefault() call to your script
$(document.body).on('submit','#sendmessagex',function(event) {
//----------------------------------------------------^^^^^
event.preventDefault();
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "/send.php",
data:str,
success: function(data) {
alert(data);
}
});
return false;
});
You have to use preventDefault() ofcourse to prevent page refresh. Then you can use the second code without datatype json. But in that case at first you have to parse the json like this way:
success: function(data){
var datax = JSON.parse(data);
//now you have object and can access like this: datax.data1, datax.data2
}
Incase you want to use first code, in php you have to set php header to define it as proper json output.
header('Content-Type: application/json');

Transfer data from Ajax to php

i am trying to send datas from ajax to php, but php doesnt show it. both scripts are on the same site: "testpage.php".
jQuery/Ajax:
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
var test = "bla";
$.ajax({
url: "testpage.php",
type: "post",
data: test,
success: function (response) {
alert("test ok");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
PHP:
<?php
if(isset($_POST["test"])) {
$test2 = $_POST;
echo $test2;
echo "Test";
}
?>
I do not see the result of PHP
use data: {test:test}, & alert your response to see your result.
success: function (response) {
alert(response);
},
Or Just append your response to html.
You need to use data: {test:sometext} if you want to do a POST request.
The PHP can't see the value in the post because you only send bla in the PHP body. You have to send test=bla. But jQuery can do it automatically by sending data : { test : test }.
$(document).ready(function() {
$("#button").click(function() {
var test = "bla";
$.ajax({
url: "testpage.php",
type: "post",
data: {
test : test
},
success: function (response) {
alert("test ok");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
You can use serialize() method into your $.ajax();
Something like:
$.ajax({
url: "testpage.php",
type: "post",
data: $("#myForm input").serialize(),
success: function (response) {
alert("test ok");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
Then try to accessing your post data by form input name.
var data = {
'test': "bla",
};
$.ajax({
type: "POST",
url: "testpage.php",
data: data,
dataType: "json"
}).done(function(response){
console.log(response);
}).fail(function(response){
console.log(response);
});

How to get the PHP var after Jquery $.ajax

I use $.ajax to send some data to testajax.phpenter code here where data are processing. Result of this proces is link. How to get access to this? I think about sessions or cookies. Set in session $test and get access in another files.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: console.log('success');
data: { json : jsonObj }
});
In testajax.php I have someting like this
echo "PDF: <a href=images/test.pdf>$dir.pdf</a>";
$test = "PDF: <a href=images/test.pdf>$dir.pdf</a>";
How to get the $test or output the echo after call $.ajax
You can use success' function to get request from PHP.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'html',
data: { json : jsonObj }
success: function(data) {
var request = data;
console.log(data);
$('#link_container').html(data);
}
});
Your console now holds PDF: <a href=images/test.pdf>($dir content).pdf</a>.
Also the variable request holds the same result that you can use anywhere in the script.
Result is appended to #link_container.
Use the success() method for display the result.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: function (data){ // <= define handler for manupulate the response
$('#result').html(data);
}
data: { json : jsonObj }
});
Use below code It may help you.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: { json : jsonObj },
onSuccess: successFunc,
onFailure: failureFunc
});
function successFunc(response){
alert(response);
}
function failureFunc(response){
alert("Call is failed" );
alert(response);
}

Categories

Resources