Getting jQuery $.post to send data to a PHP file - php

I'm trying to post some data to a PHP file using jQuery. If I send the data via a form everything works just fine, but I want it to send in the background via jQuery. The click function works (except $.post), because I have tested it with an alert() and when I comment out the $.post line everything else works. If I don't comment out the $.post line the last two lines don't work.
Here is my javascript stored in admin.js:
$(document).ready(function(){
$(".admin-refresh").click(function () {
var movieID = $(this).prev().text();
$.post("actions.php", {refreshMovie: yes, movieID: movieID});
$(this).removeClass('btn-warning');
$(this).addClass('btn-success');
});
});
Here is some of the code from actions.php. This file is working if I post the data via form.
//Refresh Movie Details
if ($_POST['refreshMovie']) {
$movieID = $_POST['movieID'];
Here is the code from active-movies.php, which contains the button that activates the javascript.
<button class="btn admin-refresh"><i class="icon-refresh"></i> Refresh</button>
The files are stored as such ROOT/admin/active-movies.php, ROOT/admin/actions.php, and ROOT/includes/js/admin.js.
Thank you for any help you can offer!

At least one of your problems is here.
{refreshMovie: yes, movieID: movieID}
should be
{refreshMovie: "yes", movieID: movieID}

Try adding a third argument to the $.post() (a callback) like:
$.post("actions.php", {refreshMovie: yes, movieID: movieID}, function(response){
// actions.php should return some data to check if the
// action was successful
// that data will be available as a variable ("response")
if ( response == 'success' ) {
// do something
} else {
// do something else
}
});

Just enclose the parameters names into quotes, because the JS will make the mistake to think that movieID:movieID is like Kung Fu Panda:Kung Fu Panda.
{'refreshMovie': 'yes', 'movieID': movieID}

Related

Ajax .post() method doesn't send data to the server [duplicate]

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

Data is not getting set in php when ajax call is successful [duplicate]

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!

Check in ajax/jquery a form beform submit ( check the value whether it is in database)

ajax is not yet sothin i master.
I have two forms field
code :
name :
and the submit button like :
<form><input type=text name=code><input type =text name=name/></form>
I would like in php/jquery to check if the code the user fill exist in a table of my db.
If it does not exits, when the user leave the textfield to fill the next one, i would like to print a message like: this code is not in the db and then clean the fied. Until the user provide a valide code.
If your php service returns true or false for validation.
and the placeholder for the error is a label called
then an example (in jQuery) would be
$(document).ready(function() {
$("form").submit(function(e) {
var code = $("input[name='code']");
var error = $("#error");
e.preventDefault();
var form = this;
$.getJSON('urlToPhp',
{ code: code.val() },
function(valid) {
if (!valid) {
error.text(code.val() + ' is not found try another code...');
code.val('');
} else {
form.submit();
}
}
);
});
});
I've created a simple example at http://jsfiddle.net/nickywaites/e4rhf/ that will show you have to create a jQuery ajax post request.
I'm not too familiar with php so that part of it I'll have to leave aside although you can use something along the lines of $_POST["Name"].
Here is php example that I googled http://php4every1.com/tutorials/jquery-ajax-tutorial/ that might be better for you.

Submit Value With Javascript

I'm a stuck with the following function:
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
parent.removeChild($child);
}
}
</script>
x
This function deletes a child element, and its content, which works great client-side! But I am wanting to pass a value to the server, in the same instance, so the content of the element can be deleted from the mysql database too. I have no idea how to do this, so any suggestions will be very appreciated!
Notes: $child, and $parent are strings generated within the php file, that I use to give each element a unique ID.
To make your life easier, use jQuery or similar framework. Here's how you would do it in jQuery:
$(function() {
$('.delete').click(function() {
var link = $(this);
var id = link.attr('id').replace('element_', '');
$.ajax({
url: 'handler.php',
data: {
element: id
},
type: 'post',
success: function() {
link.remove();
// Or link.closest('tr').remove() if you want to remove a table row where this link is
}
});
return false;
});
});
The HTML:
Remove
And handler.php:
mysql_query("DELETE FROM `table` WHERE id = '".mysql_real_escape_string($_POST['element'])."'");
Always remember to escape database input!
If you're a total noob as you said, you probably won't understand all of this so I suggest you read something about jQuery's AJAX capabilities and about overall development using jQuery or similar JavaScript framework.
Lets say I want to delete an entity using a ID
JQUERY - $.post()
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). Jquery post docs
On the server assuming you have an open database connection.
mysql_query("DELETE FROM TABLE WHERE ID = ".$_POST['ID']);
more on mysql_query found here
EDIT:
So the following will only remove the element when the ajax post is complete. Note the first arg is the url to the script that will take the action , second is the data to be sent, in this case the ID post value will be {child.id} and the third is a anon inline callback function that will take action to remove the element client side.
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
$.post('{URLTOSCRIPT}', 'ID=$child.id',function () { parent.removeChild($child); });
}}
</script>
When you call the function, you'd want to put your PHP variables in tags like so:
<?php echo $parent; ?>
and
<?php echo $child; ?>
In the function definition, you will want to get rid of the PHP style variables and use something like:
function removeElement(parentDiv, childDiv) {
//CODE
}

Categories