This is a process that I use for other ajax update functions, but for this specific instance, it doesn't want to work. I don't know if I'm missing something in my code, or if the fact that part of the query string is a url and needs to be encoded before the AJAX plugin (don't know this and couldn't find any info on it, just brainstorming).
When I access the php script directly and echo out the query, then run it in console mode, it works fine. When I try to access it with AJAX, I get the success response, but the entry is not updated in the DB, so I assume that means the script did not run properly.
Here is my code:
AJAX
jQuery('#nl-details').on('click','#d-cl-change', function(){
var mls = jQuery('#d-mls').val(),
cl = jQuery('#d-cl-input').val(),
url = 'scripts/forms/cl/clchange.php?mls='+mls+'url='+cl;
jQuery('#test').html(url); //This is just for me to view the URL
jQuery.ajax({
url: url,
dataType: 'json',
success: function(data){
jQuery('#d-cl-save').fadeIn('200').delay('800').fadeOut('800');
jQuery('#d-cl-url').html('Go to Listing');
},
error: function(){
jQuery('#d-cl-fail').fadeIn('200').delay('800').fadeOut('800');
}
});
});
PHP
//Generic include for MYSQL Credentials
define('INCLUDE_CHECK',true);
require('../../c.php');
$url = mysqli_real_escape_string($link,urldecode($_GET['url']));
$mls = mysqli_real_escape_string($link,$_GET['mls']);
$query = "UPDATE `nht_actprop`
SET CLLINK = '".$url."'
WHERE MSTMLSNO = '".$mls."'";
$result = mysqli_query($link,$query);
echo $query;
mysqli_close($link);
On this line of yor code you are missing a &
url = 'scripts/forms/cl/clchange.php?mls='+mls+'url='+cl;
I think it's supposed to be like this
url = 'scripts/forms/cl/clchange.php?mls='+mls+'&url='+cl;
I see that you have chosen a best answer already but I would just like to share with you how I would tackle this task.
I would recommend using AJAX's type option to send data via GET like this:
jQuery('#nl-details').on('click','#d-cl-change', function(){
var url = 'scripts/forms/cl/clchange.php';
jQuery('#test').html(url); //This is just for me to view the URL
jQuery.ajax({
url: url,
type: 'GET',
data: {
mls: jQuery('#d-mls').val(),
url: jQuery('#d-cl-input').val()
},
dataType: 'json',
success: function(data){
jQuery('#d-cl-save').fadeIn('200').delay('800').fadeOut('800');
jQuery('#d-cl-url').html('Go to Listing');
},
error: function(){
jQuery('#d-cl-fail').fadeIn('200').delay('800').fadeOut('800');
}
});
});
And the best part is that you don't have to change your PHP at all
Good luck! Let me know your thoughts
Related
Is it possible to mix post and get in ajax? Specifically have a form POST data to a url with get variables?
In html and PHP I would normally do this:
<form action="script.php?foo=bar" method="POST">
...insert inputs and buttons here...
</form>
And the PHP script would handle it based on logic/classes.
I have tried the following and several variations to no avail:
$(document).ready(function() {
$('#formSubmitButton').click(function() {
var data = $('#valueToBePassed').val();
$.ajax({
type: "POST",
//contentType: 'application/json',
url: "script.php?foo=bar",
data: data,
processData: false,
success: function(returnData) {
$('#content').html( returnData );
}
});
});
});
Is this even possible? If so what am I doing wrong. I do not feel as if I am trying to reinvent the wheel as it is already possible and used regularly (whether or not if it is recommended) by plenty of scripts (granted they are php based).
Please check out the below jsfiddle URL and
https://jsfiddle.net/cnhd4cjn/
url: "script.php?data="+data, //to get it in the URL as query param
data:"data="+data, // to get it in the payload data
Also check the network tab in dev tools to inspect the URL pattern on click of the submit button
You can, here's what I do.
$(document).ready(function() {
$('#formSubmitButton').click(function() {
// My GET variable that I will be passing to my URL
getVariable = $('#valueToBePassed').val();
// Making an example object to use in my POST and putting it into a JSON string
var obj = {
'testKey': 'someTestData'
}
postData = JSON.stringify(obj);
// Jquery's AJAX shorthand POST function, I'm just concatenating the GET variable to the URL
$.post('myurl.com?action=' + getVariable, postData, function(data) {
JSONparsedData = $.parseJSON(data);
nonparsedData = data;
});
});
});
I can see 1 syntax error in you code .
use
data: {data:data},
instead of
data: data,
and then try to access like
$_POST['data']; and $_GET['foo'];
But i have never tried the GET params inside a POST request :) , this is only a suggestion.
I am making a forum webpage where I'll put delete this buttons under each comment. Now when you press this button, I send the ID of the comment to PHP file using ajax which looks like this:
function Deletethis(index) {
var result = confirm("Want to delete?");
if (result==true) {
$.ajax({
url: "deletepost.php",
type: "POST",
data: index,
success: function(){
location.reload();
}
});
} else return false;
}
Now the problem is I can't receive it from the PHP end. I've used the debugger and saw that the index value is right. My PHP looks like this:
<?php
$con = mysqli_connect("localhost", "root", "123", "test") or die("DIE");
if (isset($_POST['index'])) {
$SoonToBeDeletedComment = $_POST['index'];
};
$index = intval($SoonToBeDeletedComment);
mysqli_query($con, "DELETE FROM commentsbox WHERE commentsbox.`ID` = $index");
echo "Post Deleted...";
mysqli_close($con);
?>
My code doesnt give any errors but it doesn't delete the post either. When I do the same process manually on navicat, it is working so I thought maybe the index is a string and it should be an integer. So I used intval but it didnt solve the problem either. Any ideas to help me improve my code is appreciated. Thanks in advance
In jQuery's .ajax call, the data property needs to be an object, not a string (string only it it's a full GET query string, actually, but it's not what you need here).
So, try this:
$.ajax({
url: "deletepost.php",
type: "POST",
data: {id: index},
success: function(response){
alert(response);
// location.reload();
}
});
And then in PHP, get it as:
$_POST['id']
UPDATE
Sanity checklist:
is your Deletethis function actually receiving the index?
is your ajax calling the right script?
is ajax data property an object, like I explained above?
what is the output of the PHP script?
what are the contents of $_POST?
is the id inside the $_POST array ($_POST['id'])?
does the row with that id exist in the db?
These questions should help you pinpoint the problem more accurately.
You send param to your PHP code without define his name : data: { index: index } // param : value
function Deletethis(index)
{
if ( confirm("Want to delete?") )
{
$.ajax({
url: "deletepost.php",
type: "POST",
data: {
index: index
},
success: function(){
window.location.reload();
}
});
}
}
Check also if your PHP code is working by calling page directly with param.
Hi I currently have a JS file being called to populate my html page with dynamic data. My JS file calls a PHP file to fetch stuff from my sqldb and my PHP file echos json_encode the stuff it got from the sqldb, which in turn is used to populate the html page.
My problem is that depending on what's in the url ie ?user=Bob, I want my js file to call the php file to search for Bob. Right now it searches for current user if ?user=xxxx is not specified. It seems the $GET['user'] is always null, thus it's not being passed because I suspect the JS file working as a middleman. Here are my code snippets:
My URL:
www.website.com/index.php?user=Bob
My HTML Code
<script type="text/javascript" src="js/get-data.js"></script>
My JavaScript
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
dataType: 'json',
success: function(response){
var name = response[0];
var location = response[1];
$('#name').html(name);
$('#location').val(location);
}
});
});
My PHP Code
$id;
if (isset($_GET["user"]))
{
$id = $_GET["user"];
}
else
{
$id = $_SESSION['loggedInUser'];
}
$query = "SELECT * FROM Persons WHERE User = '$user'";
if($result = mysqli_query($sqlconnection,$query))
{
$row = mysqli_fetch_row($result);
echo json_encode($row);
}
You need to specify the data attribute in your ajax call.
$.ajax({
type: 'GET',
data: $("#myForm").serialize(), //for example. You can change this to something relevant.
/*rest of the code*/
});
What this will do is prepare a GET request with the proper data, for example, http://path/to/backend/?key1=value1&key2=value2
I believe you want to do something like this
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
data: <?php echo json_encode($_GET); ?>,
dataType: 'json',
....
EDIT:
Thanks #Brad and #Ashwin Musjija for pointing out. I was focusing on answer too quickly that I overlook the possible non persistent XSS attack.
Hello i have searched the whole website for a soltution found something but didnt get it to work.
-I have the main function on the head area of the page. (This will return Data from a PHP)
-This Data i need as a variable but dont know how to handle.
function note(content,usern){
note = Function("");
$.ajax({
type: "POST",
url: "note.php",
data: {'token': content, 'user': usern }, success: function(data){ var myneededvar = data; }, }); }
Ok thats works and also data is given out
Now im calling the function in the script like this
note(token,notename);
and i need the result myneededvar
but cant get it to work.
Firstly, your variable myneededvar is local to the success handler function and will not be available outside.
Secondly, your AJAX call is asynchronous and you cannot expect to immediately get the AJAX return data in a variable right after the AJAX call statement.
i.e., you cannot do:
note(...); // call your method
alert(myneededvar); // this won't work as the AJAX call wouldn't have completed
Thirdly, not sure why you have that note = Function(""); statement there. You should remove that.
Something like this should work:
var myneededvar;
function note(content, usern){
$.ajax({
type: "POST",
url: "note.php",
data: {'token': content, 'user': usern },
success: function(data){
myneededvar = data;
// use it here or call a method that uses myneededvar
}
});
}
i have setup some ajax, which i am just testing now, pretty much the idea behind it is to send some data from dropdown boxes to a php script, do some calculations and then return the result, it does it well and returns the result, but now rather than just sending back one result and outputting that, i want to send back multiple results and output them, i am able to send multiple data to the php script, so i am sure i can send multiple back.
Anyway it only sends the first result back and not the rest.
Here is the AJAX
<script>
$("document").ready(function (){
$(".add_extension").change(function(){
var m = document.getElementById('meter_square');
var meter_square = m.options[m.selectedIndex].value;
var s = document.getElementById('story_height');
var story_height = s.options[s.selectedIndex].value;
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
statusCode: {
200: function (result, result2)
{
$("#expected_gain").html(result.value);
$("#house_price").html(result2.value2);
}
}
});
})
});
</script>
And here is the php script
<?php
$meter_square = $_GET["meter_square"];
$story_height = $_GET["story_height"];
$result = $meter_square + $story_height;
$result2 = $meter_square * $story_height;
echo json_encode(array("value" => $result, "value2" => $result2));
?>
You can see that i have already tried to give it a go from what i thought might work, if you need any other code or want me to remove the code i added which doesn't work, then let me know.
Thanks for all and any help
You're only going to receive one response object:
function (response) {
$("#expected_gain").html(response.value);
$("#house_price").html(response.value2);
}
Try this. Think it will help. No need to use status codes if u gonna use only success case
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
success: function(data){
$("#expected_gain").html(data.value);
$("#house_price").html(data.value2);
}
});