I have done this hundreds of times and it seemed to work like a charm.But I just can't figure what is wrong with this code.
$.ajax({
url:"<?php echo base_url() ?>admin/sold_item",
data:{qty:sold,tprice:sold_price,id:id,uprice:uprice},
type:"post",
async:true,
success:function(msg){
if(msg=="info_saved"){
$('#sold_data').html('Your Sold Details Have Been Saved');
setTimeout("$.colorbox.close()",1500);
// setTimeout("window.location.reload()",1800);
}
else if(msg=="wrong"){
$('#sold_data').html('Your Information is Incorrect!!Enter Data Again!!');
setTimeout("$.colorbox.close()",1500);
// setTimeout("window.location.reload()",1800);
}
}
})
I am using condition for the response.The php code called by ajax is working perfectly
this is the exact code that I am using for ajax.I have alerted the msg variable and firebug console shows the same but the if condition is just not working.What can be the reason.I have tried switch ..case but to no avail.Please somebody see what I am not seeing.
Use the developer tools in chrome and go to the network tab and then select the XHR button at the bottom left of the screen. This will show you exactly what is happening and you can read the response or see an error if there is one.
Your URL seems wrong. admin/sold_item there is no file extension.
Related
I want to begin by saying sorry for asking this question because I know this has been asked a lot on here already. I've search through the site and used Google, and looked at other examples but I can't figure out what's wrong. Running the script with FireBug running shows the POST is sent but nothing gets received. I've posted the code below.
Jquery Code:
$('#studio').submit(function (event) {
$('#formLaunch').click();
$.ajax({
url: 'test.php',
type: 'POST',
data: {
search_var: 'test'
},
dataType: 'html',
success: function (data) {
//$('#result').html(data);
alert(data);
}
});
event.preventDefault();
});
PHP Code:
<?php
$term = $_POST['search_var'];
echo $term;
?>
The end result of the code (once the AJAX request starts working) will process sent variables and echo an image which I want displayed in a DIV box on the page. For starters though just trying to get this basic 'shell' to work properly.
Thanks in advance for any help or direction.
Jeff
Always provide an error function, especially when in development. I suspect you have an error for a response (404, 500, etc). Providing an error function for debugging purposes will help you see this more quickly.
try this
$.post('test.php',{'search_var': 'test'},function(data){
alert(data);
});
Ok guys I know this question has been asked before but I am very new to PHP and JavaScript and hadn't even heard of ajax until i started looking for an answer to this question so do not understand previous answers.
I am creating a site that essentially is a bunch of videos in a SQL database, it shows one video at a time, I would like to have a next and previous video buttons.
However I cant get past this ajax thing so my question is even simpler. I have looked at this question/answer and think it pretty much sums up what im asking:
How do I run PHP code when a user clicks on a link?
I have copied that exact code,
<script type="text/javascript">
function doSomething() {
$.get("backend.php");
return false;
}
</script>
Click Me!
And in my backend.php file i have literally just got <?php echo "Hello" ?> just to test it and therefore my understanding is that when i click the link the javascript onClick event is trigged which in turn calls the backend.php file, which says to print "Hello" to the page. However when i click the link it does nothing.
Eventually obviously im going to need to get a lot more complex with my php functions and calling variables and all that stuff but i like to figure things out for myself for the most part so i learn. However im stuck on this bit. Also whilst im here i will ask another thing, I want to 'give back' to the users of the site for answering my questions but I can only really well enough in HTML and CSS to answer other peoples questions, any advice on being able to find the simpler questions on here so i can answer some.
Thanks in advance :)
It does nothing becuase you don't do anything with the result. My guess is that in the example you took, it does some work and doesn't show anything to the user. So if you just had some stuff you wanted to run on the server without returning any output to the user, you could simply do that, and it would work.
Example from jQuery's .get() documentation
What you do:
Example: Request the test.php page, but ignore the return results.
$.get("test.php");
What you want to do:
Example: Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
Take a look at the .get() documentation. You're using it incorrectly.
You should be passing data (optional) and handling the data that gets returned, at a minimum:
$.get("backend.php",
{
// data passed to backend.php goes here in
//
// name: value
//
// format. OR you can leave it blank.
}, function(data) {
// data is the return value of backend.php
// process data here
}
);
If you pass data, you can retrieve it on backend.php using $_GET. In this case:
$_GET['name'];
$.get("test.php", { name: "John", time: "2pm" }, function(data) {
alert("Data Loaded: " + data);
});
http://api.jquery.com/jQuery.get/
This would alert the data. right now that function only returns false.
$.get('backend.php', function(data) {
alert(data);
});
Your code will not print to the page the way you have it set up; you're part of the way there, in that you have called the page, but the response needs to be handled somehow. If you open up the developer tools in Chrome, you can click on the Network tab and see the request and response to verify that what you coded is actually working, but now you need to put the response somewhere.
By passing a function as the second variable into $.get, you can make your request show up on the page. Try something like this:
$.get("backend.php", function (data) { $('body').append(data); } );
Your code is not handling with that data. So instead, you should use following code :
$.get("backend.php", function(response) {
alert(response);
})
Or, to show that data on UI, assign it to any html element.
For more understanding , please visit :jQuery.get() link
Currently, I have set up an ajax call, that on change of a particular field it should execute a php script. The script first executes on page load.
AJAX Call
$j.ajax({url: prod_json_url, dataType: 'json', cache: true,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=x-user-defined' );
},
success: function(data) {
//things to do on success with JSON
}
});
Everything works great in my virtual environment for testing, but when I deploy this to a different server the following happens.
1) On page load, I can view the URL in FireBug being executed and returning the correct JSON Response. Logging shows that it did go to the script to be executed and returns the correct data. Everything acts as it should.
2) I then click to update the field. By viewing Firebug in the Console again, the correct URL is being executed, however, the JSON response is incorrect. It keeps the same one that occurred on page load. When I added logging, it appears that it never actually reaches the updated URL. (Which is the same URL as page load with updated arguments).
3) If I wait some time, and try again, it sometimes behaves as it should again, but only for the one execution.
This behavior makes me believe it is a cacheing issue. Does anyone have an idea of how I can resolve this or what variable I should be looking for or checking? The database is exactly the same and I'm not sure what else might be causing this. Any help is greatly appreciated! Please let me know if more information would be helpful as well.
Try adding the current time to the url you're loading data :
prod_json_url + '?ts=' + $.now()'
Cache control HTML headers apparently are ignore on Ajax requests in IE, therefore cache:false isn't enought. This should work though.
$.now() is a shortcut to new Date().getTime();
Set cache to false. Seems like theres client caching
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
try this copied from limk
I have a jQuery function, which is using AJAX to send the necessary information to run the respective script properly:
$("#changeUseridForm").submit(function(){
$.ajax({
type: "GET",
url: "API/root/users/changeUsername.php",
data: {
newUsername: ("#newUserid", this).val(),
password: ("#retypePass", this).val(),
xml: 1,
},
dataType: 'xml',
success: function(xml){
if($(xml).find("success").length > 0){
alert("Username changed successfully!");
$("#changeUserid").hide();
$("#BackToMainMenu").hide();
$("#MainPage").show();
$("#AddLinkButton").show();
$("#ChangeUserOptions").show();
$("#ChangeUserDataButton").show();
$("#ShowPosts").show();
}
else if($(xml).find("error").length > 0){
alert("You have to fill all the fields!");
}
}
});
return false;
});
I have several functions like this one, running perfectly; this one isn't. I verified all my variables and scripts. They're spelled correctly. It doesn't reach to the script referenced. I think the AJAX code might have a problem, but I can't detect which error is. I tried to search it on my browser's web inspector, but I can't figure it out since the page is reloading for some reason that I don't know why. (Because this function doesn't have window.location.reload() in it anywhere.)
try to set up a proxy or use firefox plugin to catch the get request(you can also use wireshark)
then you can see if there's a request to this page API/root/users/changeUsername.php
it is possible that this page API/root/users/changeUsername.php returns 302 redirect,
Check the http response of the GET Request and post it please
Look in the docs on .ajax(), you can specify an error handler function that gets details about what went wrong. That would be the first step.
You can also use Firebug's or Chrome's "Net" tab to monitor the request, and see what was returned.
You can detect (debug) a lot of errors using firebug. In this case you can use the net tab and check persists to see what request is causing reloaded page.
i make a Jquery function that (for the moment) call a function dinamically and print it with an alert. with firefox, chrome : it works! when i try on IE7 (the first time), it fails. If i reload the page (F5) and retry , it works! o_O
I FINALLY understand why that's happen. In my old website i used the jquery-1.3.2.min.js library. On this i use the jquery-1.4.2.js and in fact it doesnt work. So what's up? A bug in this new version?
cheers
EDIT
actual functions (with Bryan Waters suggestions):
// html page
prova
// javascript page
function pmNew(mexid) {
var time = new Date;
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php' + '?dummy=' + time.getTime(),
data: 'mexid='+escape(mexid)+'&id=pmnew',
success: function(msg) {
alert(msg);
}
});
return false;
}
// ajax.php
if($_POST['id']=="pmnew") {
echo "please, i will just print this";
}
Fiddler result : if i use http://localhost/website fiddler doesnt capture the stream. if i use http://ipv4.fiddler/website it capture the stream, but at the ajax request doesnt appair. if i refresh the page, yes it works. mah...i really don't know how resolve this problem...
Best way to debug is to download Fiddler and see what the HTML traffic is going on and if the browser is even making the ajax request and what the result is 200 or 404 or whatever.
I've had problems with IE cacheing even on posts. And not even sending out the requests. I usually create a date object in javascript and add a dummy timestamp just to make the url unique so it won't be cached.
ok, I'm not exactly sure what the issue is here but I think you could probably fix this by simply letting jquery handle the click instead of the inline attribute on the tag.
first change your link like this to get rid of the inline event
<a class="lblueb" href="./asynch/asynchf.php?mexid=<?$value?>"><?=value?></a>
then in your javascript in the head of your page add a document.ready event function like this if you don't already have one:
$(function(){
});
then bind a click event to your link inside the ready function using the class and have it pull the mexid from the href attribute, then call your pmNew function like so:
$(".lblueb").click(function(e){
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
Your final code should look like this:
<script type="text/javascript">
function pmNew(mexid) {
$.ajax({
type: "POST",
url: "./asynch/asynchf.php",
data: "mexid="+mexid+"&id=pmnew",
success: function(msg){
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
//document.ready function
$(function(){
$(".lblueb").click(function(e){
//prefent the default action from occuring
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
});
</script>
I believe you have an error in your SQL code. Is userd supposed to be userid?
Gaby is absolutely right that your SQL code is wide open for injection. Please consider learning PDO, which will reduce the likelihood of SQL injection significantly, particularly when using placeholders. This way you will have query($sql) and execute($sql), rather than the code going directly into your DB.
As a matter of habit you should deal with your request variables early in your script, and sanitize them to death -- then assign the cleaned results to new variables and be strict in only using them throughout the rest of the script. As such you should have alarm bells ringing whenever you have a request variable in or near an sql query.
For example at the very least you should be stripping any html tags out of anything that will get printed back to the page.
That is in addition to escaping the quotes as part of the sql string when inserting into the database.
I'm all for coding things up quickly -- sure, neaten up your code later... but get security of request vars right before doing anything. You can't tack on security later.
Anyway sorry for harping on.... as for your actual problem, have you tried what Gaby suggested: change your html to:
<a class="lblueb" href="#" onclick="return pmNew('<?php echo $value; ?>')"><?php echo $value; ?></a>
And then update your JS function to:
function pmNew(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php',
data: 'mexid=' + escape(mexid) + '&id=pmnew',
success: function(msg) {
$('#pmuser').html('<a class="bmenu" href="./index.php?status=usermain">PANEL (' + msg + ')</a>');
}
});
return false;
}
Also, with IE -- check the obvious. Clear the browser cache/history
I didn't understood the "fail", but here's another example..
function pmNew(mexid) {
$.post("./asynch/asynchf.php", {mexid: mexid, id: "pmnew"},
function(msg) {
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
It appears that this issue is faced by several people.
One of them had luck with clean installation of browser:
http://www.geekstogo.com/forum/topic/22695-errorpermission-denied-code0/
Check to make sure the content returned to the DOM is valid for the DOCTYPE specified.
I've had a similiar problem with Chrome, FF and Safari all working just fine, but finding the ajax result broken in IE. Check to make sure you don't have any extra divs or spans in the ajax result breaking your markup.