jquery not post data in IE - php

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

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

Using POST data in a query with Ajax and 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.

JSON data not being sent in POST?

I'm building an AJAX form and I'm trying to send 3 fields by JSON.
Client-side, the form is serialised and entered into JSON format:
$('#form-signin').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel2';
$.ajax({
type: "POST",
url: url,
data: $.base64.encode($('#form-signin').serialize()),
dataType: 'json',
success: function(data, status) {
$.getJSON(url, function(data) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
});
}
});
event.preventDefault();
});
Server side, my router splits the URL request up, sees that the first part contains 'ajax' then proceeds to specially pass the routing request to an AJAX handler.
my problem is that even inside the router, checking $_REQUEST, which is what is used to get the information about the post, the post data is not there. The same goes with $_POST.
Even the first page where the request hits (index.php), $_REQUEST does not have the data.
What am I doing wrong?
Server Side,
The request is sent to an index.php which includes the Autoloader and init script.
The init script initialises the database connection, sets the error, exception and session handling, then passes the request onto the router.
The router, in its construction method: sets the URL as an array (exploded $_SERVER['REQUEST_URI']), and then sets the relevant controller, method and additional parameters.
In this case, as we are doing an ajax request, special processing happens before we dispatch the request.
The method parameters are set to:
$requestParams = $_REQUEST;
unset($requestParams['url']);
This request parameter(s) along with additional information (url, controller, method and database object) are passed for dispatch.
In all cases, we are primarily dispatching using this method:
$dispatchedController = new $this->controller($this->database);
$method = $this->method;
return $dispatchedController->$method($this->params);
If I remember right from using a plugin a long time ago, the method $.base64.encode() returns a single string so what you are probably sending to the server is something like a single parameter with no value.
I believe you should be doing something like
data: "foo=" + $.base64.encode($('#form-signin').serialize()),
You are not sending json to the server just a base64 encoded string. Also you are expecting key/pair values. To send key/pair values just pass the serialized form data to the $.ajax function.
$('#form-signin').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel2';
$.ajax({
type: "POST",
url: url,
data: $('#form-signin').serialize(),
dataType: 'json',
success: function(data, status) {
$.getJSON(url, function(data) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
});
}
});
event.preventDefault();
});
The code should work (assuming your HTML is not the problem here, e.g., '#form-signin' is the right selector for the right form).
You mentioned you are not able to get the data on the server side. However, are you absolutely sure you are even sending the data you need from the client? For example, have you analyzed the request using a tool such as Firebug?

PHP: Multiple ajax request

I want a code for multiple ajax request. What happens actually is my first ajax request give me the response and in that responce function i m calling another function which having another website url. I want to send data to this new website using multiple ajax request.
Please help me out...
Thanks,
Prafulla
use global variables and manipulate your data in each request.
like:
var a;
$.ajax({
url:url_one;
success: function(data){ a =data; }
});
$.ajax({
url:url_two;
data: a //sends the data from the 1st request
success: function(data){
//do something with the data from the 2nd url
}
});
You can encapsulate your ajax call in function or event handlers as you need.
You can also manuipulate the data returned in variable a before sending it to the 2nd url.
Seems sloppy to me, but sould work.

Reading from a MYSQL table every 5 seconds and dynamically displaying results on a PHP page without refreshing

I'm looking to display data from a table in a mysql database using PHP, however, I want the data to automatically update itself and retrieve current values every 5 seconds.. WITHOUT having to refresh the page. Is this possible? Maybe with JQuery/ AJAX? If so, please explain how it can be done / point me to a resource where I can find such information
Thanks
If you use window.setInterval() and jQuery's .load() you should be able to do what you want. The PHP script should return the HTML that needs to replace the previous one.
Javascript:
function refreshData()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#container').load('path/to/script.php');
}
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
A really basic example:
function poll(){
$.ajax({
type: "GET",
url: "your/php/script/",
success: function(data){
// do something with data
}
});
};
setInterval(poll, 5000);
jQuery is a good option. Here are the docs for ajax.
You will want to make this call with setInterval
Something like this might get your started.
setIntervla(updateFromDb,5000);
function updateFromDb(){
$.ajax({
url: "getUpdates.php",
success: function(){
$(this).addClass("done");
}
});
};
What you are describing is exactly the type of the AJAX is used for, AJAX allows for asynchronous requests to be made to your server.
For learning I would suggest using a framework like Jquery and look into the AJAX api.
Basicly you will need a PHP script that query the database and responds the results the way you want them. A suggestion would be to JSON encode them.
In JavaScript on the client you will need to you things like:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "yourpage.php",
success: function(data){
//HANDLE DATA
// use JSON.parse(data); if your JSON encoding your data
}
});
},5000)
Just go to the documentation of jQuery:
http://api.jquery.com/category/ajax/
Use the command "jQuery.get()" or better "jQuery.getJson()" to make a http request to the server. Use JSON to get a better communication between server and client. Return from server side a json string and convert this on the client to an javascript object. (the function jQuery.getJson already do this for you) so you can easily access the key and values in the data array.
Just an example:
SERVER Part with PHP:
<?
$data = array('key'=>'value');
return json_encode($data, true);
CLIENT Part:
$.getJSON('myurl.php', function(data) {
// THIS ONE IS CALLED with your PHP data
alert(data.key);
});
$(function(){
window.setInterval(function(){
$.post("filename.php",{'field1':field1,'field2':field2,'field3':field3},function(data){
//callbackfunction(data)
})
},30000);//millisecs
});
And have your php file do all your sql

Categories