jQuery $.ajax POST function into WPSC - php

I am using Wordpress Shopping cart. I want to append or modify the product name based on 3 variations the same thing goes for the price to.
I have tried to implement a simple Jquery on click event to an image using the AJAX $.post method within the single product page. It's not sending the data value even if I encode it with JSON. I must say that I'm new with JSON and PHP. Thanks in advance !
In the single product page
$(function() {
$('#div_img_link').click(function() {
$.ajax({
type: 'POST',
data: "test value",
// dataType : "json",
url: '../wpsc-cart_widget.php',
cache:false
});
});
});
In wpsc-cart_widget.php
$name=wpsc_cart_item_name();
if (isset($_POST['data'])){
$value1 = $_POST['data'];
}else{
$value1 = "";
}
echo "$name $value1";
I know that are some similar posts out there I've read them all can't figure it out. I want to know if the WPSC can perform the jQuery POST function without refreshing the page. Any help will be greatly appreciated!!
schematics
EDIT
SCHEMATICS 2 - to be more concise !
What I'm trying to accomplish

SEA, you're missing a function to handle the response that comes back from the server.
I would expect to see something like this :
$(function() {
$('#div_img_link').click(function() {
$.ajax({
url: '../wpsc-cart_widget.php',
type: 'POST',
data: "test value",
dataType : "JSON",
cache:false,
success: function(data) {
//do something here with the data.
//eg.
alert(data);
},
error: function() {
//do something here if an error occurs.
//eg.
alert("an error occurred");
},
});
});
});
The best place to learn more about ajax is the ajax() page in the jQuery API documentation.
You also need to ensure that the server response and the client expectation are compatible. With a client expectation of dataType: "JSON", you must ensure that the server returns a json-encoded response. Json-encoding is only necessary for multiple data in a single response. A single data item can be sent unencoded.
EDIT:
After seeing your Schematic 2, I think your ajax request data should look something like this :
data: {
'pid': '12345678',
'quantity': '1'
),
where pid is the "product id" and quantity is how many of the product the user wants to add to his/her basket.
But surely the WPSC documentation includes examples of this stuff? You shouldn't have to work it out for yourself.

Related

php value is in the name of the array

I'm not the best to explain problems but i'll try my best.
So i'm developping a website with php and javascript and bootstrap.
I got a list of equipment that i want to be able to edit with a modal form.
What i'm doing is that i write the id of the equipment (from mysql) into the id of the picture that i'm supposed to click to edit the equipment.
Like this
When i'm clicking on it it goes to a JS page that execute an ajax request to get all the infos from the database.
Now the main problem: when i transfer the id with the ajax request (with $_POST) and i var_dump it to see if i really have it it shows like that: Array ( [1] => )
The number is actually the ID but i have no idea how to use it as a string to get my infos.
If I get you right, your question is "How can I fix the ajax request to process it in PHP?"
Without seeing the specific code-part that you need help with, it's difficult to tell what exactly needs to be changed.
From your description, I assume that your Ajax request in JS looks like this
// your code is either this:
jQuery.post( 'https://example.org?' + id );
// or this:
jQuery.post( 'https://example.org', id );
This will give you the URL https://example.org?1, which is equal to the URL https://example.org?1= (i.e., param "1" is an empty string)
You need to give the ID a param name. Like this:
// This will work (add the string before the parameter value "id=")
jQuery.post( 'https://example.org?item=' + id );
// This is even better - set the post data as object:
jQuery.post( 'https://example.org', { 'item': id } );
In PHP you can then access the product id via $_POST['item'].
Of course, you can use any other param instead of "item" and even pass multiple values inside the post object.
Update based on new comment
The problem is, that you only pass the ID to the post-request, without assigning a name to it: data: id
Change this to data: {item: id} and you have $_POST['item'] in PHP. Here's the full code:
$.ajax({
url: "getInfos.php",
type: "POST",
data: {item: id}, // <-- change this line!
success:function(response){
$('#bodyEdit').html(response);
$('#myModalEdit').modal('show');
},
error:function (resultat, statut, erreur){
console.log(resultat, statut, erreur );
}
})
EDIT: the answer above works better, it seems i've got more than one problem for this issue and the answer above helped me correct it for good
thanks to everyone that answers my question,
i found out about the problem.
First i was the ajax function built in jquery:
$.ajax({
url: "getInfos.php",
type: "POST",
data: {item: id}, // <-- change this line! credit to Philipp
success:function(response){
$('#bodyEdit').html(response);
$('#myModalEdit').modal('show');
},
error:function (resultat, statut, erreur){
console.log(resultat, statut, erreur );
}
});
I was sending the id with data: but the value was missing .serialize after it, wich adapt the value to the url query if i understood correctly.
working code:
$.ajax({
url: "getInfos.php",
type: "POST",
data: id.serialize(),
success:function(response){
$('#bodyEdit').html(response);
$('#myModalEdit').modal('show');
},
error:function (resultat, statut, erreur){
console.log(resultat, statut, erreur );
}
});

Using Tagit with PHP and MySQL: Generating Tags From Database

So I'm new to jQuery and I am trying to use Tagit to create dynamic tags. What the script offers is the ability to show a list of possible tags for the user to click on and have as one of their tags. This list though is populated by a Javascript array and the variable is called availableTags.
What I want to do is query a MySQL database for tags and have this happen every time a key is pressed.
I need some help determining how to do this with the jQuery code...
Here is the source code for Tagit
I have a function that uses JSONP but I would rather use JSON and modify the hidden select element's id and value so I could easily post this to my php script.
For some reason my function won't work and the script won't return any values.
This is what I have so far: (you can see the whole code here)
$(function() {
$('#demo3').tagit({
tagSource:function( request, response ) {
$.ajax({
url: "http://girlzunderground.com/php/profile-tags.php",
dataType: "jsonp",
data: {
txt: $("#test1").val(),
t: "books"
},
success: function( data ) {
response( data );
}
});
},
triggerKeys:['enter', 'comma', 'tab'],
allowNewTags: true
});
});
What your trying to do is going to have a lot overhead involved and is not really going to scalable at all.
Regardless, you can bind an event to the input with jquery
http://api.jquery.com/keyup/
Then have that do an ajax query [ http://api.jquery.com/jquery.ajax/ ] which will be a seperate server side script that gets the keywords from your database. Once you have your ajax response you are going to have to import it into tagit. Looks like the documentation in your link shows you how to do this...I haven't used this script before....looks like calling the add action is what you are looking for. You need to make sure you don't have duplicates of course.
Well I got it figured out. One main problem I was having was I wasn't sending the header for JSON data. I needed to specify this header before the JSON would actually work. Also had to use request.term to populate the txt data varialbe.
$(function() {
$.ajaxSetup({ cache: false });
$('#demo3').tagit({
tagSource:function( request, response ) {
$.ajax({
url: "php/profile-tags.php",
dataType: "json",
data: {
txt: request.term,
t: "books"
},
success: function( data ) {
response( data );
}
});
},
triggerKeys:['enter', 'comma', 'tab'],
allowNewTags: true
});
});

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.

no data from callback, jquery ajax json, php, amazon

I've been trying the code at: https://gist.github.com/Exeu/4674423 this is a code that connects to amazon wsdl and retrieve product information. so far I have not been able to make it work. The code consist of a index.html, ama_funtion.js, search.php, AmazonECS.class.php. The index file loads and you insert the item name you want choose the category and other params, then when you click in the search link it goes to the ama_function.js and it make and ajax request to the search.php which have the passwords and keys to connect to the wsld, then it request the info from Amazon and return it as JSON to ama_function.js.
I have test ama_funtions.js to see if the index.html file connects to it, and it does, I did put an alert to show the input in the search box at index.html. Also I have test the search.php, I have manualy put the values in the search.php file and it connects to amazon and retrieve the product information as JSON object. the problem is that there is not a success callback as no data return to ama_funtions.js from search.php to be rendered. I know this as I tested it by adding an error function
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
error: function () {
alert("NO DATA");
},
and it did show me the alert, also I have tried to change the ->
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
for ->
data: {
q : value,
category : cat,
country : country,
page : page }
nothing works I am crazy looking to solve this, I will appreciate someone that help us with this. Please see a working example which belong the person sharing the code -> http://amazonecs.pixel-web.org. This is the way is suppose to work but it doesn't.
Regards
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
error: function () {
alert("NO DATA");
},
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
data: {
q : value,
category : cat,
country : country,
page : page
}
})

jQuery/Ajax SQL live update via PHP help

I have a table that outputs all my contacts via a while loop from my database.
my syntax is like this:
SELECT * FROM contacts WHERE id = $_SESSION['user_id'] ORDER BY name ASC LIMIT 5
that pulls out all my data and only gives me 5 results.
Now my goal is to have a little button that opens up a model box with jquery (this I can manage on my own) with a form asking the user to input a number then that number will be sent via post or get to $PHP_SELF and update a local variable with the number the user inputed, then that variable will be used to update the database to increase or decrease the LIMIT value.
I have looked all over the web (with google) to look for submitting a form using AJAX but all the examples i've found don't work for me.
When the user submits the number and the sql query is executed and updated for the outputed table to dynamically update according to the new LIMIT value all without ever refreshing the page to the user.
my jquery code is:
(document).ready(function(){
$("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({
type: "post",
url: "process.php",
data: "val="+ val,
cache: false,
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
});
return false;
});
});
$(document).ready(function(){ $("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({ type: "post", url: "process.php", data: "val="+ val, cache: false, success:
function(){
$('form#form').hide(function(){$('.success').fadeIn();});
} }); return false; }); });
then my php code is:
$new_val = $_POST['new_val'];
$_val = "UPDATE `settings` SET `display_limit` = {$new_val} WHERE `user_id` = {$_SESSION['user_id']}";
mysql_query($_val) or die(mysql_error());
and my form is simple:
any suggestions? I haven't come to how to have my outputed table dynamically update yet so if anyone can point me in the right direction or provide some help that would be awesome.
thanks
EDIT:
Here is an updated jquery script I was working on, I'm able to submit the form successfully! but my only problem is that I can't see the changes until the page is refreshed with defeats the purpose of the AJAX usage... sigh
how can I now have my #results div updated and refreshed with the form submission content?
$(document).ready(function() {
var options = {
url: 'process.php',
type: 'post',
//dataType: 'json',
target: '#last_five_sellers',
success: success
};
// bind to the form's submit event
$('#form').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
function success(responseText, $form) {
$("form#form").hide();
$(".success").fadeIn();
}
});
In your php code where you do the update, You could echo your contacts in html-format. That would then return to your success function in jquery.
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
The function have a parameter data, which is the html-format you echoed in php.
Example
success: function(data){
$('form#form').hide(function(){$('.success').fadeIn();});
$(data).appendTo('#result');
}
You need to understand the flow of a request. Once the php script runs, that is it, it is done. If you plan on submitting back to that same page, it'll be a new request and a new execution of that script. Now, you could add a special case to that script to return the necessary data to your jQuery code, but that's messy IMO. I would rather have a separate script to handle that functionality. This can be looked at as a web service.
So, when a you go to that page in a browser, it will intially display 5 contacts (or w/e the default you have in the LIMIT clause). When you click the icon to display more contacts, you employ jQuery to submit a GET request to that 'web service' page (it really should be GET, since you're retrieving data, not submitting new data). This would then be a list of contacts that you use to update the display on the page, using jQuery/JavaScript.
As noted by Codler, the output from that 'web service' can be HTML which you simply use to replace the existing HTML which displays the contacts. (This would be the preferred way. You almost always want do as much on the server as you reasonably can.)
It looks like your jQuery code is duplicated — there's no need to bind the form's submit event twice. Additionally, the first jQuery block is missing the opening dollar-sign ("$"). And as far as I know, .hide() does not support passing a callback through the first parameter. In the jQuery API documentation, it's written as .hide( duration, [ callback ] ).
I would write:
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(){
$("form#form").hide();
$('.success').fadeIn();
}
});
return false;
});
});
Now, if you want to update your results table dynamically, the simplest way is just to replace the entire thing with the updated HTML. So for instance, if you modified your PHP script (process.php) so that, after updating display_limit, it outputted the new results table, you could then write something like (assuming your results table is table#results):
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(data){
$("form#form").hide();
$(".success").fadeIn();
$("#results").replaceWith(data);
}
});
return false;
});
});
You just have to make sure your script only outputs HTML.
Contrary to what George answers above, HTML will definitely work for this purpose, but I think the ideal method is to send purely the data alone (minus structure/presentation) in either JSON or XML format, and then use JavaScript to build the HTML; you can save a lot of bandwidth this way, and ultimately build a much more responsive application.
EDIT
Here's a mini JSON-based example.
JavaScript:
$(function(){
$("#form").submit(function(){
var val = $("input[name=new_value]").val();
$.getJSON("process.php?val=" + val, function(data){
$("#results").empty();
$(data.rows).each(function(){
$("#results").append('<tr><td>' + this.column_a + '</td><td>' + this.columbn_b + '</td></tr>');
});
});
return false;
});
});
PHP (process.php):
[assuming you already have a result/rows called $result]
$json = array('rows' => array());
while ($row = mysql_fetch_assoc($result)) {
$json['rows'][] = $row;
}
echo json_encode($json);
Now, granted, I haven't tested this code at all, but it should give you the gist of it.

Categories