Using POST data in a query with Ajax and PHP - php

I have a website that uses bootstrap tabs so I'm trying to make everything work with minimal refreshing with Ajax, however I'm having trouble with getting an ajax post to work with a mysql query until the page is refreshed.
Once a button is pressed the value is grabbed from the ID of that element by Ajax and a bootstrap tab is opened. This is where I want the data to be passed so the results are relevant to the option that the user has selected.
Modules.php
(Ajax request)
$(".completed").click(function() {
var element = $(this);
var ID = $(this).attr("id");
var dataString = 'id='+ ID;
$.ajax({
cache: false,
url: "includes/scripts/ajax/module_parts.php",
type: "POST",
datatype: "text",
data: dataString,
success: function (html) {
$('#moduleNum').html(ID);
console.log(ID);
},
error: function(data, errorThrown)
{
alert('request failed :'+errorThrown);
}
});
return false;
});
module_parts.php
$module_id = mysqli_real_escape_string($connection, $_POST['id']);
echo $module_id;
$query = mysqli_query ($connection, "SELECT number FROM Modules WHERE number = '".$module_id."'");
I know that the post is working correctly because I tried turning the post into a session then when refreshing the page the data was displayed.
Also the data is displaying correctly when appending the ID to an html element.
Many thanks,
Zack.

Just as a side note, I prefer to do this with ajax shenanigans. It may help you ...
Altered the anchor element:
Click me
Javascript:
ID = $(this).attr("id")
$('body').on('click', '[rel="completed"]', function() {
$.post('includes/scripts/ajax/module_parts.php', { id : ID }, function(data) {
$('#moduleNum').html(data); // data or ID ?
}).fail(function() {
alert('request failed');
});
});
The $('body').on part helps to keep scripts alive should you insert new links or buttons. It means anything within the body tag but you can and maybe should narrow it down further such as the surrounding div.
I, personally, find this way to be easier to deal with, especially if there is just simple data passing to and fro.

1) Check if id is passed by post and get by module_parts.
2) I'd rather use object when passing post data via ajax:
data: { id : ID }
3) Good option to check ajax requests is to use Firebug (on Console), you can check requests details without echoing.

At least two things in your script need resolution.
datatype should be changed to dataType (text is not one of jQuery's "intelligent guess" types (xml, json, script, or html), so dataType must be correctly spelled.
You should prevent the default behavior of the anchor click event.
(".completed").click(function(e) {
e.preventDefault
...
There may be some additional problems, but these two jumped out at me.

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

Pass external URL into ajax javascript

I am trying to fetch the contents of an external XML URL, into the javascript's ajax script, but it simply won't accept it, due to CROSS domain issue. I have searched through google regarding this issue, but nothing good so far, everything I've read so far stated that I need to incorporate PHP as well, but with that, the page would take reload.
I simply want that when a user enters a number that number gets passed as an argument in the URL, then displays the XML content in the screen without reloading.
SO any help will be highly appreciated.
Here's my code so far.
<script>
function myFunction() {
$("#dvContent").append("<ul></ul>");
$.ajax({
type: "GET",
url: "http://lx2.loc.gov:210/lcdb?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=1&query=bath.isbn%3D9781452110103",
dataType: "xml",
success: function(xml){
$(xml).find('record').each(function(){
var sTitle = $(this).find('datafield[tag="245"]').find('subfield[code="a"]').text();
var sAuthor = $(this).find('datafield[tag="100"]').find('subfield[code="a"]').text();
var sIsbn = $(this).find('datafield[tag="020"]').find('subfield[code="a"]').text();
$(".mypanel").html(text);
});
$("<li></li>").html(sTitle).appendTo("#dvContent ul");
$("<li></li>").html(sAuthor).appendTo("#dvContent ul");
$("<li></li>").html(sIsbn).appendTo("#dvContent ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
</script>

jquery not post data in IE

i create one simple form in which i have one combobox when i am selecting any thing i put one function onchange event so its call.
then i send this data in one helper file through jquery
<script type="text/javascript">
$.noConflict();
function Searchwine(obj,str) {
{queryString: ""+str+""}, function(data){
jQuery.post("http://www.site.com/search/helper/autosuggest.php", {queryString: ""+str+""}, function(data){
if(data.length >0) {
jQuery('#windatano').html(data);
}
</script>
i am using this code for post data in autosuggest from through javascript and print replay of jquery in windatano id
--> its working fine in crome and ff and other all browser but in IE its not working
Can any help?
Thanks,
You're using jQuery improperly.
The proper syntax is (for POST)
$.post([URL], {
var: value,
var2: value
}, function(data) {
//callback goes here
}
);
If you want to pass in the querystring as though it's a GET, just append it to the URL after a ?.
E.G.:
"http://www.site.com/search/helper/autosuggest.php?" + str
IE does not support cross domain ajax calls regardless if its getJSON or not. learned that the hard way... i ended up adding a local php file that used curl to get the results and return them to the script, its the only way to make ie work with cross domain requests.
You can't do cross domain ajax requests, if the request url is in another domain, this fail, if the domain is the same, use a relative path:
jQuery.post("/search/helper/autosuggest.php"....
If you need Cross domain ajax request, you have to use jsonp (http://api.jquery.com/jQuery.getJSON/#jsonp)
And if you are using post method, the queryString define a get vars, you need use data option
jQuery.ajax({
url: '/search/helper/autosuggest.php',
type: 'POST',
data: data,
sucess: function (data) {
if (data) jQuery('#windatano').html(data);
}
});
When data can be the object format:
var data = {
a_var = 'value',
other_var: 'other value'
};
Sorry my English

jquery update html with returned mysql data after POST

I have a jquery/php voting system I'm working on. Once a user clicks a vote button a jquery modal pops open and they must confirm their vote by clicking "Confirm". This will send an ajax request to update the database and what not. After clicking confirm the modal will close. I would like to be able to update the number of votes dynamically on the page. I can easily grab that data from the mySQL table. My question is how does this get sent back for me to then update the html page dynamically?
Currently the page does nothing, so to the user it doesn't look like they've voted. Ideally I'd want to update the total number of votes and also inject an image that shows what they voted for.
function vote(el, id) {
$.ajax({
type: 'POST',
url: '/path/morepath/',
dataType: 'json',
data: {
'action': 'castVote',
'vote': id
},
success: function (data) {}
});
$.modal.close();
}
On the server side, respond to the POST request with a JSON object containing the number of votes and possibly the image path.
Then inside the AJAX callback, data will be that object. Then you can use jQuery to select an element in the DOM and call .text() or .html() on it to update the content.
If you're passing poorly formed data back from PHP, you can make it a bit better by giving it some structure and then making it json for javascript's ease-of-use:
$sqlResult = ...;
$responseArray = array();
$responseArray['result'] = true; //or false if it failed
$responseArray['data'] = $sqlResult;
print json_encode($responseArray);
Before you can really expect the page to respond properly to an ajax response, you must be sure your response data is being parsed correctly.
Inside of your success function, try console.log'ing your response to see what it looks like
console.log(data);
if there is something you can reference in the return data that is reliable, do a check for it:
success: function(data) {
if(data.result == 'true') {
$('someElement.someClass').someFunction();
}
}
You can change the value or html content of the voting number using a few different options such as:
...
success: function(data)
{
var $newTotal = ...//get total from data
$('voteCountContainer').html($newTotal); // or you can also use .val() if it's an input
}
...
Hope that helped,
Dan

jQuery/Ajax SQL live update via PHP help

I have a table that outputs all my contacts via a while loop from my database.
my syntax is like this:
SELECT * FROM contacts WHERE id = $_SESSION['user_id'] ORDER BY name ASC LIMIT 5
that pulls out all my data and only gives me 5 results.
Now my goal is to have a little button that opens up a model box with jquery (this I can manage on my own) with a form asking the user to input a number then that number will be sent via post or get to $PHP_SELF and update a local variable with the number the user inputed, then that variable will be used to update the database to increase or decrease the LIMIT value.
I have looked all over the web (with google) to look for submitting a form using AJAX but all the examples i've found don't work for me.
When the user submits the number and the sql query is executed and updated for the outputed table to dynamically update according to the new LIMIT value all without ever refreshing the page to the user.
my jquery code is:
(document).ready(function(){
$("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({
type: "post",
url: "process.php",
data: "val="+ val,
cache: false,
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
});
return false;
});
});
$(document).ready(function(){ $("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({ type: "post", url: "process.php", data: "val="+ val, cache: false, success:
function(){
$('form#form').hide(function(){$('.success').fadeIn();});
} }); return false; }); });
then my php code is:
$new_val = $_POST['new_val'];
$_val = "UPDATE `settings` SET `display_limit` = {$new_val} WHERE `user_id` = {$_SESSION['user_id']}";
mysql_query($_val) or die(mysql_error());
and my form is simple:
any suggestions? I haven't come to how to have my outputed table dynamically update yet so if anyone can point me in the right direction or provide some help that would be awesome.
thanks
EDIT:
Here is an updated jquery script I was working on, I'm able to submit the form successfully! but my only problem is that I can't see the changes until the page is refreshed with defeats the purpose of the AJAX usage... sigh
how can I now have my #results div updated and refreshed with the form submission content?
$(document).ready(function() {
var options = {
url: 'process.php',
type: 'post',
//dataType: 'json',
target: '#last_five_sellers',
success: success
};
// bind to the form's submit event
$('#form').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
function success(responseText, $form) {
$("form#form").hide();
$(".success").fadeIn();
}
});
In your php code where you do the update, You could echo your contacts in html-format. That would then return to your success function in jquery.
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
The function have a parameter data, which is the html-format you echoed in php.
Example
success: function(data){
$('form#form').hide(function(){$('.success').fadeIn();});
$(data).appendTo('#result');
}
You need to understand the flow of a request. Once the php script runs, that is it, it is done. If you plan on submitting back to that same page, it'll be a new request and a new execution of that script. Now, you could add a special case to that script to return the necessary data to your jQuery code, but that's messy IMO. I would rather have a separate script to handle that functionality. This can be looked at as a web service.
So, when a you go to that page in a browser, it will intially display 5 contacts (or w/e the default you have in the LIMIT clause). When you click the icon to display more contacts, you employ jQuery to submit a GET request to that 'web service' page (it really should be GET, since you're retrieving data, not submitting new data). This would then be a list of contacts that you use to update the display on the page, using jQuery/JavaScript.
As noted by Codler, the output from that 'web service' can be HTML which you simply use to replace the existing HTML which displays the contacts. (This would be the preferred way. You almost always want do as much on the server as you reasonably can.)
It looks like your jQuery code is duplicated — there's no need to bind the form's submit event twice. Additionally, the first jQuery block is missing the opening dollar-sign ("$"). And as far as I know, .hide() does not support passing a callback through the first parameter. In the jQuery API documentation, it's written as .hide( duration, [ callback ] ).
I would write:
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(){
$("form#form").hide();
$('.success').fadeIn();
}
});
return false;
});
});
Now, if you want to update your results table dynamically, the simplest way is just to replace the entire thing with the updated HTML. So for instance, if you modified your PHP script (process.php) so that, after updating display_limit, it outputted the new results table, you could then write something like (assuming your results table is table#results):
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(data){
$("form#form").hide();
$(".success").fadeIn();
$("#results").replaceWith(data);
}
});
return false;
});
});
You just have to make sure your script only outputs HTML.
Contrary to what George answers above, HTML will definitely work for this purpose, but I think the ideal method is to send purely the data alone (minus structure/presentation) in either JSON or XML format, and then use JavaScript to build the HTML; you can save a lot of bandwidth this way, and ultimately build a much more responsive application.
EDIT
Here's a mini JSON-based example.
JavaScript:
$(function(){
$("#form").submit(function(){
var val = $("input[name=new_value]").val();
$.getJSON("process.php?val=" + val, function(data){
$("#results").empty();
$(data.rows).each(function(){
$("#results").append('<tr><td>' + this.column_a + '</td><td>' + this.columbn_b + '</td></tr>');
});
});
return false;
});
});
PHP (process.php):
[assuming you already have a result/rows called $result]
$json = array('rows' => array());
while ($row = mysql_fetch_assoc($result)) {
$json['rows'][] = $row;
}
echo json_encode($json);
Now, granted, I haven't tested this code at all, but it should give you the gist of it.

Categories