Posting data from ajax to php - php

Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.

Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);

If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});

Related

jQuery Ajax return html AND json data

I'm not sure if there is any way to do this or not, but this would solve so many of my problems if there is a simple solution to this.
What I need/want to be able to do is return HTML and JSON in my success of ajax request. The reason being, I want to request a file and return all of that page, but I also want to be able to return a specified set of information from the page in json, so I can use it for other things.
This is what I'm doing now:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
}
});
This is what I'd like to be able to do:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
$("title").html(json.PageTitle)
}
});
on the page that is being returned, I would specify what I want the title to be. (For instance, if it's a profile, I would return the user's name)
HTML and data wrapped in JSON
You can do it by returning a 2 element JSON array.
The first element contains HTML and the second element contains another JSON array with the data inside. You just need to unwrap it carefully without breaking anything.
Serverside
$html = '<div>This is Html</div>';
$data = json_encode(array('page_title'=>'My Page'));
$response = array('html'=>$html, 'data'=>$data);
echo json_encode($response);
Clientside
//Ajax success function...
success: function(serverResponse){
$("body > .container").html(serverResponse.html);
var data = JSON.parse(serverResponse.data);
$("title").html(data.page_title)
}
Note 1: I think this is what #hakre meant in his comment on your question.
Note 2: This method works, but I would agree with #jheddings that its probably a good idea to avoid mixing presentation and data. Coding karma will come back to bite.
Trying to mix the retun value to contain presentation and data seems like a potential for confusion. Why not split it into two calls and fetch the data on success of the other?
Something like:
$.ajax({
type: "POST",
url: "inc/"+view_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html) {
$("body > .container").html(html);
$.ajax({
type: "POST",
url: "inc/"+data_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(json) {
$("title").html(json.PageTitle);
}
});
});
You also have the option of including the data in html5 data attributes
For instance, if you're returning a list of Animals
<ul id="ZeAnimals" data-total-animals="500" data-page="2">
<li>Cat</li>
<li>Dog</li>
...
</ul>
You can then collect the data you require using
$('#ZeAnimals').data('total-animals')
Sometimes separating your request into two different ajax calls makes sense also.
You may use a library that does that automatically, like http://phery-php-ajax.net. Using
Phery::instance()->set(array(
'load' => function(){
/* mount your $html and $json_data */
return
PheryResponse::factory()
->json($json_data)
->this() // points to the container
->html($html);
}
))->process();
$(function(){
var $container = $('body > .container');
$container.phery('make', 'load'); // or $container.phery().make('load')
$container.bind('phery:json', function(event, data){
// deal with data from PHP here
});
$container.phery('remote');
});
You may, as well, use phery.views to automatically load a portion of the site automatically, without having to worry about client-side specific code. You would have to put a unique ID on the container, container in this example:
$(function(){
phery.view({
'#container': {}
});
});
Phery::instance()->views(array(
'#container' => function($data, $params){
/* do the load part in here */
return
PheryResponse::factory()
->render_view($html)
->jquery('.title')->text($title);
}
))->process();

How to pass multiple parameters by jQuery.ajax() to PHP?

I have a simple load more style script that works fine on the index page, where only one parameter is sent via ajax
$(function() {//When the Dom is ready
$('.load_more').live("click",function() {//If user clicks on hyperlink with class name = load_more
var last_msg_id = $(this).attr("id");//Get the id of this hyperlink this id indicate the row id in the database
if(last_msg_id!='end'){//if the hyperlink id is not equal to "end"
$.ajax({//Make the Ajax Request
type: "POST",
url: "index_more.php",
data: "lastmsg="+ last_msg_id,
beforeSend: function() {
$('a.load_more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("ul#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
});
With this HTML/PHP
<div id="more">
<a id="<?php echo $msg_id; ?>" class="load_more" href="#">more</a>
</div>
However, I want to add another php variable so that it can also work with particular categories, I have no problems writing the HTML and PHP but I am new to Jquery and struggling to edit the script to include the additional parameter if it is set. This is the HTML that I am thinking of using, just struggling with editing the JQuery
<div id="more"class="<?php echo $cat_id;?>">
<a id="<?php echo $msg_id;?>" class="load_more2" href="#">more</a>
</div>
As always any help is much appreciated!
You can set
data = {onevar:'oneval', twovar:'twoval'}
And both key/value pairs will be sent.
See Jquery ajax docs
If you look under the data section, you can see that you can pass a query string like you are, an array, or an object. If you were to use the same method you already are using then your data value would be like "lastmsg="+ last_msg_id + "&otherthing=" + otherthing,
You can pass multiple URL params in the data portion of your ajax call.
data: "lastmsg="+ last_msg_id +"&otherparam="+ other_param
On the PHP side, you'd just process these as you already are.
You can use this code:
$.ajax({//Make the Ajax Request
type: "POST",
url: "index_more.php",
data: {var1: "value1", var2: "value2"},
beforeSend: function() {
$('a.load_more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("ul#updates").append(html);//Append the html returned by the server .
}
});
Try It:
data: JSON.stringify({ lastmsg: last_msg_id, secondparam: second_param_value});
You can add more parameters separating them by comma (,).

PHP + Jquery - pass value through ajax to php and check against variable

I can't get the following PHP + jQuery to work - all I want the script to do is pass the value through ajax, and get the php to grab it, check it matches and add 1 to score.
This is the code I've written:
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}else{
//Do nothing
}
echo $score;
?>
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
var value = "145";
alert(value);
$.ajax({
url: 'processing.php', //This is the current doc
type: "POST",
data: ({name: value}),
success: function(){
location.reload();
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
Thanks for the help, I've changed GET to POST in both instances, and no joy - there's something else wrong.
First of all: Do not go back to the dark ages... don't use the same script to generate HTML and to respond to an ajax request.
I can't make any sense of what you are trying to do... Let me change your code so it at least makes some sense and document what's going on. It seems like the problem is the fact that you are calling location.reload from your success handler.
// ajax.php - Outputs 2 if the name parameter is 145, 1 otherwise (????)
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}
echo $score;
?>
// test.html
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
// Why were you reloading the page? This is probably your bug
// location.reload();
// Replace the content of the clicked paragraph
// with the result from the ajax call
$("#raaagh").html(data);
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
You use POST in your jQuery, but you try and get a GET in you php.
BTW it is good practice to check if a GET/POST variable is set before reading it.
using the isset() function.
Replace $_GET with $_POST and there you are.
Basically POST and GET are two different way to pass variables to a script. The get method in php can also be attached at the end of a url : script.php?variable=value and it is really easy to hack. While the post method can be submitted with forms or ajax calls and it is pretty safe, at least more than the get.
Also i'd suggest you to check whatever a GET or POST variable is set before calling it, so that you can prevent stupid notice errors.
Just use the following code:
if (isset($_POST['var']) and !empty($_POST['var'])) { // do something }
You can also delete the
}else{
// do nothing
}
part of the script, since the else clause it is not necessary always.
You're submitting the data with an Ajax POST, but trying to read it out of a GET. Either use type: "GET" in your Ajax call or $_POST['name'] in your PHP.
The problem is you are using jQuery to POST your value, yet you are reading it with GET.
You should be able to fix your problem by changing your $_GET['name'] to $_POST['name']

Sending a value from a dropdown box to PHP via jQuery

I'm trying to take values from a dropdown two boxes and send them to a PHP file which will draw an appropriate field from a mySQL database depending on the combination chosen and display it in a div without refreshing the page using AJAX. I have the second part sorted, but I'm stuck on the first part.
Here is the HTML: http://jsfiddle.net/SYrpC/
Here is my Javascript code in the head of the main document:
var mode = $('#mode');
function get() {$.post ('data.php', {name: form.him.value, the_key: #mode.val()},
function(output) {$('#dare').html(output).show();
});
}
My PHP (for testing purposes) is:
$the_key = $_POST['the_key'];
echo $the_key;
After I have it in PHP as a variable I can manipulate it, but I'm having trouble getting it there. Where am I going wrong? Thanks for your replies!
You need a callback function as well to have the server response to the POST.
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
This snippet will post to ajax/test.html and the anonymous function will be called upon its reply with the parameter data having the response. It then in this anonymous function sets the class with result to have the value of the server response.
Help ? Let me know and we can work through this if you need more information.
Additionally, $.post in jQuery is a short form of
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
your jquery selectors are wrong:
html:
<select id="mode">
jquery selector:
$("#mode").val();
html:
<select name="player">
jquery selector:
$("select[name=player]").val();
You want to add a callback to your ajax request, its not too hard to do, here ill even give you an example:
$.ajax({
url: "http://stackoverflow.com/users/flair/353790.json", //Location of file
dataType: "josn",//Type of data file holds, text,html,xml,json,jsonp
success : function(json_data) //What to do when the request is complete
{
//use json_data how you wish to.;
},
error : function(_XMLHttpRequest,textStatus, errorThrown)
{
//You fail
},
beforeSend : function(_XMLHttpRequest)
{
//Real custom options here.
}
});​
Most of the above callbacks are optional, and in your case i would do the following:
$.ajax({
url: "data.php",
dataType: "text",
data : {name: ('#myform .myinput').val(),the_key: $('#mode').val()},
success : function(value)
{
alert('data.php sent back: ' + value);
}
});​
the ones you should always set are url,success and data if needed, please read The Documentation for more information.

JQuery to PHP function and back Ajaxed

i have a set of php function that i want to call on different events mostly onclick with jquery async (ajax).
The first function is called on load
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
success: function(html)
{
$("#div1").show('slow').html(html)
}
});
The Data: {'func':'1'} --> is a switch statement on the php side
switch($_POST['func'])
{
case '1':
getParents();
break;
case '2':
getChilds(params);
break;
case '3':
getChildObjects(params);
break;
default:
}
"This functions are calls to a soap server" <-- irrelevant.
So when that function finishes i get an array which contains IDs and Names. I echo the names but i want the ID for reference so when i click on the echoed name i can call an other php function with parameter the ID of the name...
How do i get rid of the switch statement?? How do i call properly php functions and pass params to it??? How can i save this IDs so when i click on an item with that id an other php function is called??
Plz feel free to ask any question, any answer is welcome :)
``````````````````````````````EDIT``````````````````````````````````````````
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: 'post',
async: true,
url: "Parents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
success: function(json_data)
{
$("#div1").empty();
$.each(json_data, function(key, value)
{
$("#div1").append('<p class="node"><b>['+key+']</b> => '+value+'</p>');
$(this).data('id', key);
});
}
});
$("p.node").click(function()
{
var id = $(this).data('id');
alert('The ID is: ' + id);
});
});
I got json communication working but my problem is the data stuff,
when i click on a node the id is undefined... it gets printed but when i click on it oupsss.. so the problem is how can i properly attach the ID to each corresponding .. .
You can avoid the switch statement by using an MVC framework that routes your request to the proper function. For example, using CodeIgniter REST Server, you might have the following URL's to your functions:
http://myserver/my_api/parents
http://myserver/my_api/children
http://myserver/my_api/childObjects
You can then POST the parameters along with each AJAX request.
You would probably also want to return the ID you pass as part of the response, so it will be available when you make a request for the next function.
One solution for managing your ID's would be to encode your data as JSON. This will allow you to pass the whole PHP array to Javascript, and have it natively understand and read the ID's and Names.
To encode your PHP array as JSON, try this:
echo json_encode($my_array);
(You'll need PHP 5.2+ for this to work)
This will print out JSON data when the page is requested. Next, in your JavaScript add a "dataType" argument to your Ajax function call. Something like this:
// Get JSON Data and Save
$.ajax({
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
dataType: "json",
success: function(json_data) {
$("#div1").data(json_data);
}
});
// Display the ID when clicked
$("#div1").click(function(){
var id = $(this).data('id');
alert('The ID is: ' + id);
});
This tells the Ajax function to expect JSON back.
When the success function is called you can access the "json_data" variable and find all the ID's and Names just as you had them in PHP. You'd then need to write some code to appropriately save those ID's and Names. They can then be used later on (ie. when you click on the button etc).
EDIT: I've updated the code above. The JSON data is now associated with the HTML element "#div1", so you can refer back to it in the future. I've also added a simple click event. Whenever the element is clicked, it's ID will be displayed.

Categories