I'm trying to send a JavaScript variable to a php script using ajax. This is my first time using ajax and I don't know where I went wrong. Here's my code
function selectcat(v) {
$.ajax({
type: "GET",
url: "myurl.php",
dataType: "script",
data: { "selected_category" : v}
}).done(function() {
window.location.href = "http://mywebsite.com";
});
}
All help is appreciated
Here's the HTML
<ul class="cat">
<li class="opt" onclick="selectcat('option1')">option1</li>
<li class="opt" onclick="selectcat('option2')">Option 2</li>
</ul>
This is the ajax php file
<?php
session_start();
$ctgry = $_GET['selected_category'];
$_SESSION['select_cat'] = $ctgry;
?>
You need to remove dataType: "script" since you are just sending data. Do it like this:
function selectcat(v) {
$.ajax({
type: "GET",
url: "myurl.php",
data: {"selected_category": v}
}).done(function(result) {
console.log(result);
//window.location.href = "http://mywebsite.com";
});
}
Hi this is what I do to call an ajax request
You can post data or load a file using following code:
$("#button click or any other event").click(function(){
try
{
$.post("my php page address",
{
'Status':'6',
'var one':$("#myid or .class").val().trim(),
'var 2':'var 2'
}, function(data){
data=data.trim();
// alert(data);
// this data is data that the server sends back in case of ajax request you
//can send any type of data whether json or or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
I hope this help!
AJAX is easier than it sounds. You just need to see a few good examples.
Try these:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
The above examples demonstrate a few things:
(1) There are four formats for an AJAX request - the full $.ajax() structure, and three shortcut structures ($.post(), $.get(), and $.load() )
Until you are pretty good at AJAX, I suggest using a correctly formatted $.ajax() code block, which is what the above examples demonstrate. Such a code block looks like this:
$('#divID').click({
$.ajax({
type: 'post',
url: 'contact.php',
dataType: 'json',
data: 'email=' + form.email.value
}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
return false;
} else {
alert('Failed to connect to the server.');
return false;
}
}
});
});
(2) In an $.ajax() code block, the data: line specifies the data that is sent to the PHP processor file.
(3) The dataType: line specifies the type of data that the ajax code block expects to receive back from the PHP processor file. The default dataType is html, unless otherwise specified.
(4) In the PHP processor file, data is returned to the AJAX code block via the echo command. Whether that data is returned as html, text, or json, it is echoed back to the AJAX routine, like this:
<?php
//perform MySQL search here. For eg, get array $result with: $result['firstname'] and $result['lastname']
$out = '<div id="myresponse">';
$out .= 'First Name: <input type="text" value="' .$result['firstname']. '" />';
$out .= 'Last Name: <input type="text" value="' .$result['lastname']. '" />';
$out .= '</div>';
echo $out;
Please try a couple of the above examples for yourself and you will see how it works.
It is not necessary to use json to send/return data. However, json is a useful format to send array data, but as you can see, you can construct a full html response on the PHP side and echo back the finished markup.
So, you just need to echo back some data. It is the job of the PHP file to:
(1) receive the data from the AJAX routine,
(2) Use that data in a look up of some kind (usually in a database),
(3) Construct a response, and
(4) echo (NOT return) the response back to the AJAX routine's success: or .done() functions.
Your example could be changed to look something like:
HTML:
<ul class="cat">
<li class="opt" value="TheFirstOption">option1</li>
<li class="opt" value="The Second Option">Option 2</li>
</ul>
javascript/jQuery:
$('.opt').click(function(){
var v = $(this).val();
$.ajax({
type: "POST",
url: "myurl.php",
dataType: "html",
data: { "selected_category" : v}
}).done(function(data) {
$('#div_to_insert_the_response').html(data);
});
});
PHP:
<?php
$val = $_POST['selected_category'];
echo 'You selected: ' . $val;
dataType: "script" has no sense here, I think you want json or leave it empty.
Your PHP script should work if you try to get the variable with $_GET['selected_category']
I suggest you this modification to help yourself for debugging
$.ajax({
type: "GET",
url: "myurl.php",
data: { "selected_category" : v},
success: function(data){
console.log(data);
// you can also do redirection here (or in complete below)
},
complete: function(data){
// when request is done, independent of success or error.
},
error: function(data){
// display things to the user
console.error(data);
}
})
Related
So I've followed all your advice about making an jQuery or Javascript AJAX request to a php file on a server.
The problem I'm running in to is that my response is this
Fatal error: Array callback has to contain indices 0 and 1 in
So here is my jQuery
$(document).ready(function(){
$(".ex .select").click(function(){
$("body").data("id", $(this).parent().next().text());
Those lines serve to capture a variable and save it as data on the body element, so I can use it later.
But I want to send that same variable to PHP file, to add to a complex API request - eventually to return the results, create $_SESSION variables and so forth
var pageId = {
id: $("body").data("id"),
};
But let's avoid that as a problem and just make my array simple like
var pageId = {
id: "12345",
};
$.ajax({
type: 'GET',
url: 'test.php',
data: pageId,
datatype: 'json',
cache: false,
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
});
});
And for now at least I was hoping to keep my PHP file simple for testing my grasp of the concepts here
<?php
$id = $_GET('id');
echo json_encode($id);
?>
I'm expecting the response
Data: 12345
Status: Success
But I get the Error Message above.
You need to change $_GET('id') to $_GET['id']
and in order to send status, you need to add status to an array just like below and try to parse JSON on your response.
<?php
$id = $_GET['id'];
$result = array("id"=>$id, "Status"=>"Success");
echo json_encode($result);
?>
And access in jquery using . like if you use data variable in success then
success:function(data){
alert(data.Status);
}
change $id = $_GET('id'); to $id = $_GET['id'];
because $_GET, not a function it's an array type element.
I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.
I want passing 2 parameters to PHP page via AJAX and load the response, but this code is not working.
JavaScript:
$(".show_category").click(function(){
var category_id = $(this).attr('data-category');
$.ajax({
url: "conx.php",
method: "POST",
data: {
action: "sort_category",
category_id: category_id
},
success: function(data) {
$("#con").load("conx.php");
}
});
});
PHP:
<?php
echo "1".$_POST["action"]."<br/>";
?>
You issue is here:
success: function(data) {
$("#con").load("conx.php");
}
At this point, you have already posted the data and received the HTML response. There is no need to make another HTTML request by calling .load, and doing so will mean requesting it again without the POST data, so it will not have the intended effect. Just use the HTML you already have in the data argument.
success: function(data) {
$("#con").html(data);
}
On a side note, this PHP code is a reflected XSS vulnerability:
<?php
echo "1".$_POST["action"]."<br/>";
?>
I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);
I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});