Getting multimple results from Ajax post - javascript

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

Related

PHP Form submit get return value to html [duplicate]

I want to alert the return value from a php method, but nothing happens. Here is the ajax and php methods. Can anyone see what I am doing wrong?
--------------------------------------…
Ajax script
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data');
}
});
--------------------------------------…
php method
function junk($id)
{
return "works11";
}
in PHP, you can't simply return your value and have it show up in the ajax response. you need to print or echo your final values. (there are other ways too, but that's getting off topic).
also, you have a trailing apostrophe in your alert() call that will cause an error and should be removed.
Fixed:
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
PHP:
function junk($id)
{
print "works11";
}
You have an extra ' in there on the alert(data') line
This should work
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
And your PHP code should call the method also and echo the value
function junk($id) {
return 'works11';
}
exit(junk(4));
All you're doing currently is creating the method
ajax returns text, it does not communicate with php via methods. It requests a php page and the return of the ajax request is whatever the we babe would have showed if opened in a browser.

How to intercept POST data with Javascript

I am using this javascript function to send data to my php script (via POST) I am then using this information to retrieve data from my database and I would like to reuse the information retrieved in my JavaScript code.
Here is my code :
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function() {
// HERE I would like to inctercept the data that my php script put in myFunctions.php produces and use it to generate content;
}
});
});
So basically, when clicking on the button #validerChoixDeCours, my code sends some data to myFunctions.php which generates a response stored in a php variable and I want to use that response in my JS code.
Thank you in advance for your help :)
Its actually quite easy!
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(e) {
e contains the response from the php script
}
});
});
The first parameter of success contains the response from the request. so, in this case, the 'e' variable contains the output which you can use.
Add data variable
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(data) {
alert(data);
}
});
});
make sure your server side code look like this
<?php
$output = "Any String or Array";
echo json_encode($output);
?>

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

checking JSON data with jQuery

I have written a php script:
cch.php:
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
json_encode($array);
$stmtcheck->close();
And jquery for submitting form is
recover.php:
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function()
{
}
});
});
The script is returning more than one variable and the returned data should be in JSON format.
How do I read the data in jQuery?
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function(data) //parameter missing
{
var json = $.parseJSON(data);
console.log(json);
//in console you will get the result response
}
});
});
Hello your php code should echo the JSON output like this:
<?php
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
$stmtcheck->close();
echo json_encode($array);
?>
Now, in your javascript, you can use JSON.parse method to get the JSON.
Also, specifying your response type as JSON will automatically return a JSON object.
$("#formUnlock").submit(function (e) {
e.preventDefault();
$.ajax({
url: '../scripts/cch.php',
method: 'POST',
data: $('#formUnlock').serialize(),
dataType: 'JSON',
success: function (json_string) {
var res = JSON.parse(json_string);
console.log(res);//This should output your JSON in console..
}
});
});

Parse JSON data in jQuery and display in textfield

I am going to print the response data from test.php in JSON format to print it on particular field
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = $.parseJSON(response);
$(document).ready(function(){
$("#test").click(function(){
$("#bemail").val(result.email);//when i prints only result than it displays [object object]
});
});
}
});
Try it like this . You have to put your ajax inside $(document).ready
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = JSON.parse(response);
$("#bemail").val(result.email);
}
});
});
you are calling document.ready() inside the AJAX success handler which doesn't get invoked since AJAX call doesn't invoke the document loading again, DOM has already loaded and it loads only once in the life cycle of a page session.
This much should do
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = JSON.parse(response);
$("#bemail").val(result[0].email); //after you explained the JSON response
}
});
Your code is totally wrong, it should be
function displayEmail() {
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = $.parseJSON(response);
//Just Print the Result in Console using console.log(result)
$("#bemail").val(result.email);
}
});
}
$(document).ready(function() {
$("#test").click(function() {
displayEmail();
});
});

Categories

Resources